gpt4 book ai didi

python - 为什么 Popen 子进程不会死亡?

转载 作者:行者123 更新时间:2023-11-30 22:32:46 26 4
gpt4 key购买 nike

我正在使用 Popen 启动一个子进程,我希望它能够完成退出。然而,进程不仅没有退出,而且向它发送 sigkill 仍然让它活着!下面是一个演示的脚本:

from subprocess import Popen
import os
import time
import signal

command = ["python","--version"]

process = Popen(command)
pid = process.pid

time.sleep(5) #ample time to finish

print pid

print "Sending sigkill"
os.kill(pid,signal.SIGKILL)

try:
#Kill with signal 0 just checks whether process exists
os.kill(pid,0)
print "Process still alive immediately after (not so bad...)!"
except Exception as e:
print "Succeeded in terminating child quickly!"

time.sleep(20) #Give it ample time to die

#Kill with signal 0 just checks whether process exists
try:
os.kill(pid,0)
print "Process still alive! That's bad!"
except Exception as e:
print "Succeeded in terminating child!"

对我来说,这打印:

77881
Python 2.7.10
Sending sigkill
Process still alive immediately after (not so bad...)!
Process still alive! That's bad!

此脚本不仅可以验证子进程在应该完成后是否仍然存在,而且我可以在打印的进程 ID 上使用 ps 并查看它是否仍然存在。奇怪的是, ps 将进程名称列为 (Python) (注意括号)。

最佳答案

您需要调用 process.wait() ,或使用signal.signal(signal.SIGCHLD, signal.SIG_IGN)一次表明您不打算等待任何 child 。前者是可移植的;后者仅适用于 Unix(但为 POSIX-standard )。如果你不做这些事情,在 Unix 上,进程将像僵尸一样徘徊,而 Windows has a similar behavior if you keep the process handle open .

关于python - 为什么 Popen 子进程不会死亡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45362807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com