2
我有一个大脚本设计来运行一个任务,一次。但是我有一个init脚本,它使用start-stop-daemon在任何时候杀死脚本。该脚本结束很好,但子流程命令运行直到它完成。我怀疑它可能只是一个问题,我如何试图做全局变量。或者,我使用communicate与子进程。无论如何这里的代码相关的东西:蟒蛇杀子进程通信退出
import subprocess
import os
import signal
pro = ''
def sigHandler(signum, frame):
global pro
os.killpg(pro.pid, signal.SIGTERM)
sys.exit()
def run(data):
#I found an example using preexec_fn somewhere on stackoverflow. Cant
#remember if they were using .communicate() or not
global pro
pro = subprocess.Popen(command, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = False, preexec_fn = os.setsid).communicate()
return(1)
if __name__ == '__main__':
signal.signal(signal.SIGTERM, sigHandler)
while True:
run(relevantData)
看来,直到子进程已经完成了可变亲没有得到数据。所以当sigterm在子进程运行时运行时,不会有pid数据被杀死。这可能是communic()的一个特性。我想用wait()来代替,但是我用命令的输出来解决缓冲区问题。 – ryan461