Python Process不会调用atexit

时间:2010-03-30 15:07:19

标签: python multiprocessing terminate atexit

我正在尝试在atexit中使用Process,但遗憾的是它似乎无效。这是一些示例代码:

import time
import atexit
import logging
import multiprocessing

logging.basicConfig(level=logging.DEBUG)

class W(multiprocessing.Process):
    def run(self):
        logging.debug("%s Started" % self.name)

        @atexit.register
        def log_terminate():
             # ever called?
             logging.debug("%s Terminated!" % self.name)

        while True:
            time.sleep(10)

@atexit.register
def log_exit():
    logging.debug("Main process terminated")

logging.debug("Main process started")

a = W()
b = W()
a.start()
b.start()
time.sleep(1)
a.terminate()
b.terminate()

此代码的输出为:

DEBUG:root:Main process started
DEBUG:root:W-1 Started
DEBUG:root:W-2 Started
DEBUG:root:Main process terminated

我希望在调用W.run.log_terminate()a.terminate()时调用b.terminate(),并且输出为likeo(强调添加)!:

DEBUG:root:Main process started
DEBUG:root:W-1 Started
DEBUG:root:W-2 Started
DEBUG:root:W-1 Terminated!
DEBUG:root:W-2 Terminated!
DEBUG:root:Main process terminated

为什么这不起作用,当Process被终止时,是否有更好的方法来记录消息(来自Process上下文)?

感谢您的投入 - 非常感谢。

解决方案

编辑:根据Alex Martelli建议的解决方案,以下工作符合预期:

import sys
import time
import atexit
import signal
import logging
import multiprocessing

logging.basicConfig(level=logging.DEBUG)

class W(multiprocessing.Process):
    def run(self):
        logging.debug("%s Started" % self.name)

        def log_terminate(num, frame):
             logging.debug("%s Terminated" % self.name)
             sys.exit()
        signal.signal(signal.SIGTERM, log_terminate)
        while True:
            time.sleep(10)

@atexit.register
def log_exit():
    logging.debug("Main process terminated")

logging.debug("Main process started")
a = W()
b = W()
a.start()
b.start()
time.sleep(1)
a.terminate()
b.terminate()

值得注意atexit文档中的以下注释:

注意:当程序被信号杀死,检测到Python致命内部错误或调用os._exit()时,不会调用通过此模块注册的函数。

1 个答案:

答案 0 :(得分:18)

正如the docs所说,

  

在Unix上,这是使用SIGTERM完成的   信号;在Windows TerminateProcess()上   用来。注意退出处理程序和   最后的条款等,不会   执行。

如果你在Unix上,你应该能够用signal拦截SIGTERM,并执行你需要的任何“终止活动”;但是,我不知道跨平台的解决方案。