每个进程调用一次信号处理程序

Signal handler being called once per process

我有一个生成多个进程的程序,我用 Ctrl+C 终止了它。

在程序开始时,我捕获信号以执行一些清理操作。

def cleanup(*_):
    # do cleanup operations here
    # ...
    exit(1)

# trap ctrl+c and hide the traceback message
signal(SIGINT, cleanup)

# spawn processes (pool of workers) and do work here
# ...

问题是 cleanup 被多次调用(每个 运行 进程调用一次)。

我怎样才能做到 cleanup 只被调用一次?

您的子进程正在从其父进程继承信号处理程序。如果您希望处理程序仅在一个进程中执行,您可能希望在子进程中注销该处理程序。