【问题标题】:Gracefully Terminate Child Python Process On Windows so Finally clauses run在 Windows 上优雅地终止子 Python 进程,以便最终子句运行
【发布时间】:2013-11-12 22:18:41
【问题描述】:

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

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

(这些东西可能嵌入在诸如 close 之类的上下文中 - 通常围绕硬件锁定/数据库状态)

问题是我无法找到在 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 事件 - 什么也没做。

有没有人有办法做到这一点,以便子进程可以清理?

【问题讨论】:

  • 在系统中放置一个文本文件,孩子们会定期检查他们是否应该退出......肯定会......但可能有更好的方法或打开某种套接字服务器听着
  • 您是否已经在使用signal() 为 kill -HUP 注册信号处理程序?
  • 顺便说一句,右起:stackoverflow.com/questions/5033277/… 几乎正是您所需要的......
  • 啊,你的权利......我的错......阅读理解失败......编辑说它可能也可以在这里应用
  • 如果您可以从陷阱中引发异常,信号陷阱和不优雅的循环就会得到解决——我认为捕手实际上不会因为来自其他地方的信号而得到异常。我将在星期一在目标系统上进行测试。

标签: python windows subprocess


【解决方案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

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多