执行_sleep.py
import os
import time
import subprocess
sleep_script = 'sleep_forever.py'
child = subprocess.Popen(sleep_script,
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
subout = child.communicate()[0]
print subout
rc = child.returncode
sleep_forever.py
#!/usr/bin/python
import time
while True:
time.sleep(1)
当我运行 execute_sleep.py 然后 kill -TERM -- -<pid of execute_sleep.py>
时,
execute_sleep.py 终止,但 sleep_forever.py 继续运行。
我该怎么做才能在 execute_sleep.py 收到信号时向下传播到 sleep_forever.py?
这些选项中的任何一个都会阻止信号吗?
-
shell=True
-
close_fds=True
- 使用
subprocess.PIPE
最佳答案
您需要处理信号,否则您将创建孤儿(sleep_script 进程)。因此,当终止父进程的信号被捕获时,它会传播到之前的子进程。
def handler(signum, frame):
functionToKillSleeper(pidtokill)
signal.signal(signal.SIGTERM, handler)
注意不能捕获SIGKILL。
所以你需要 SIGINT 或 SIGTERM 父进程以便处理信号,否则你的问题将仍然存在。
关于python - 子进程 Popen : signal not propagating,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39604228/