import asyncio import functools import os import signal """ 信号值 符号 行为 2 SIGINT 进程终端,CTRL+C 9 SIGKILL 强制终端 15 SIGTEM 请求中断 20 SIGTOP 停止(挂起)进程 CRTL+D """ def exit(sign_name): print(f"获取信号{sign_name}: exit") loop.stop() loop = asyncio.get_event_loop() for sign_name in ('SIGINT', 'SIGTERM'): loop.add_signal_handler(getattr(signal, sign_name), functools.partial(exit, sign_name)) print(" Ctrl+C 停止运行.") print(f"pid {os.getpid()}: 发送 SIGINT 和 SIGTERM 信号退出循环") try: loop.run_forever() finally: loop.close()