在Windows上优雅地终止Python子进程,以便Finally子句运行

2024-05-15 02:51:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

(这些东西可以嵌入到closer这样的上下文中,通常是围绕硬件锁定/数据库状态)

问题是我找不到一种方法在Windows中给孩子发信号(就像在Linux环境中一样),这样它就可以在终止之前运行清理。我认为这需要使子进程以某种方式引发异常(就像Ctrl-C那样)。在

我尝试过的事情:

  • 在os.杀死在
  • 在操作信号在
  • subprocess.Popen使用creationFlags并使用ctypes.windll.kernel32.GenerateConsoleCtrlEvent(1, p.pid)abrt信号。这需要一个信号陷阱和不优美的循环来阻止它立即中止。在
  • ctypes.windll.kernel32.GenerateConsoleCtrlEvent(0, p.pid)-ctrl-c事件-什么也没做。在

有没有人有一个可靠的方法来做这个,这样子进程就可以清理干净了?在


Tags: 方法信号进程场景原因resctypespid
1条回答
网友
1楼 · 发布于 2024-05-15 02:51:21

我可以让GenerateSolectLevent像这样工作:

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"

输出

^{pr2}$

相关问题 更多 >

    热门问题