如果进程终止,请执行某些操作
Do something if process is terminated
如果一个进程正在 运行ning 并且例如用户通过任务管理器意外终止或机器重新启动(因此强制终止进程),我如何注册这样一个事件,该进程将执行一些完全终止之前的任务?
我尝试失败的是:
from signal import signal
from signal import SIGTERM
def foo():
print('hello world')
if __name__ == '__main__':
signal(SIGTERM, foo)
while True:
pass
我将从命令行 运行 执行此操作,然后导航至任务管理器并结束任务,但从未调用 foo
。
根据对 Can I handle the killing of my windows process through the Task Manager? 的回答 - 任务管理器似乎使用不可屏蔽的信号(相当于 Linux 的 SIGKILL
)终止进程。这意味着你无法捕捉到它。
有other signals you can catch in Windows,如SIGBREAK
、SIGCHLD
、CTRL_C_EVENT
和CTRL_BREAK_EVENT
,但我猜任务管理器不使用任何这些用于终止进程。
如果一个进程正在 运行ning 并且例如用户通过任务管理器意外终止或机器重新启动(因此强制终止进程),我如何注册这样一个事件,该进程将执行一些完全终止之前的任务?
我尝试失败的是:
from signal import signal
from signal import SIGTERM
def foo():
print('hello world')
if __name__ == '__main__':
signal(SIGTERM, foo)
while True:
pass
我将从命令行 运行 执行此操作,然后导航至任务管理器并结束任务,但从未调用 foo
。
根据对 Can I handle the killing of my windows process through the Task Manager? 的回答 - 任务管理器似乎使用不可屏蔽的信号(相当于 Linux 的 SIGKILL
)终止进程。这意味着你无法捕捉到它。
有other signals you can catch in Windows,如SIGBREAK
、SIGCHLD
、CTRL_C_EVENT
和CTRL_BREAK_EVENT
,但我猜任务管理器不使用任何这些用于终止进程。