优雅地终止子Python进程在Windows上,所以最后的子句运行

时间:2013-11-01 16:53:58

标签: python windows subprocess

在Windows框中,我有许多场景,其中父进程将启动子进程。由于各种原因 - 父进程可能想要中止子进程但是(这很重要)允许它清理 - 即运行finally子句:

try:
  res = bookResource()
  doStuff(res)
finally:
  cleanupResource(res)

(这些东西可能嵌入在像关闭器这样的上下文中 - 通常围绕硬件锁定/数据库状态)

问题是我无法找到在Windows中发信号通知孩子的方法(就像我在Linux环境中那样),因此它会在终止之前运行清理。我认为这需要让子进程以某种方式引发异常(如Ctrl-C所示)。

我尝试过的事情:

  • os.kill
  • os.signal
  • subprocess.Popen使用creationFlags并使用ctypes.windll.kernel32.GenerateConsoleCtrlEvent(1, p.pid) abrt信号。这需要一个信号陷阱和不良循环来阻止它立即中止。
  • ctypes.windll.kernel32.GenerateConsoleCtrlEvent(0, p.pid) - ctrl-c event - 什么也没做。

有没有人有这样做的确定方法,以便子进程可以清理?

1 个答案:

答案 0 :(得分:1)

我能够让GenerateConsoleCtrlEvent像这样工作:

import time
import win32api
import win32con
from multiprocessing import Process


def foo():
    try:
        while True:
            print("Child process still working...")
            time.sleep(1)
    except KeyboardInterrupt:
        print "Child process: caught ctrl-c"

if __name__ == "__main__":
    p = Process(target=foo)
    p.start()
    time.sleep(2)

    print "sending ctrl c..."
    try:
        win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0)
        while p.is_alive():
            print("Child process is still alive.")
            time.sleep(1)
    except KeyboardInterrupt:
        print "Main process: caught ctrl-c"

输出

Child process still working...
Child process still working...
sending ctrl c...
Child process is still alive.
Child process: caught ctrl-c
Main process: caught ctrl-c
相关问题