我想在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()会被调用,并且输出被什么东西likeso(强调):

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马尔泰利建议的解决方案,如所预期以下工作:

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()被调用杀死不叫从这个模块中注册的功能
有帮助吗?

解决方案

的文档说,

  

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

如果你是在Unix上,你应该能够拦截SIGTERM用的信号,并执行任何‘终止活动,’你需要;然而,我不知道一个跨平台解决方案的

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top