【发布时间】:2017-08-22 16:10:42
【问题描述】:
我有两个 python 脚本如下 -
父.py
import os
import signal
shutdown = False
def sigterm_handler(signum, frame):
global shutdown
shutdown = True
if __name__ == '__main__':
signal.signal(signal.SIGTERM, sigterm_handler)
signal.signal(signal.SIGINT, sigterm_handler)
os.chdir(os.path.dirname(os.path.abspath(__file__)))
cmd = 'python child.py'
while True:
if shutdown == True:
break
print 'executing %s' % cmd
exit_code = os.system(cmd)
print 'Exit Code from %s > %s' % (cmd, exit_code)
print 'Exiting Parent'
child.py
import signal
import time
shutdown = False
def sigterm_handler(signum, frame):
global shutdown
shutdown = True
if __name__ == '__main__':
signal.signal(signal.SIGTERM, sigterm_handler)
signal.signal(signal.SIGINT, sigterm_handler)
while True:
if shutdown == True:
break
print 'Child Process Running !!'
time.sleep(1)
如果我运行 parent.py 并在终端上按 ctrl + c,则子进程退出并由父进程重新启动,因为父进程未处理 SIGINT 未由父进程处理。如果在终端上按下 ctrl + c,我想终止父母和孩子。但是对于孩子因为一些错误而不是 ctrl + c 事件而退出的情况,我希望父母继续执行。我本可以在父级中处理 SIGCHLD ,但这并不表明子级是否由于 ctrl + c 事件或其他原因而退出。我将如何实现这种行为?
下面是我运行父级时得到的输出 -
executing python child.py
Child Process Running !!
Child Process Running !!
Child Process Running !!
Child Process Running !!
^CExit Code from python child.py > 2
executing python child.py
Child Process Running !!
Child Process Running !!
Child Process Running !!
Child Process Running !!
Child Process Running !!
^CExit Code from python child.py > 2
executing python child.py
Child Process Running !!
Child Process Running !!
Child Process Running !!
Child Process Running !!
^CExit Code from python child.py > 2
............................
............................
【问题讨论】:
标签: python subprocess signals os.system