Skip to main content
 首页 » 编程设计

python之子进程 Popen : signal not propagating

2025年04月02日8shanyou

执行_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 父进程以便处理信号,否则你的问题将仍然存在。