【发布时间】:2016-12-14 05:43:03
【问题描述】:
我正在尝试为我的 python 守护进程创建类似于 supervisor 的东西,并发现相同的代码在 python2 中有效,在 python3 中无效。
一般来说,我已经来到了这个最小的示例代码。
daemon.py
#!/usr/bin/env python
import signal
import sys
import os
def stop(*args, **kwargs):
print('daemon exited', os.getpid())
sys.exit(0)
signal.signal(signal.SIGTERM, stop)
print('daemon started', os.getpid())
while True:
pass
supervisor.py
import os
import signal
import subprocess
from time import sleep
parent_pid = os.getpid()
commands = [
[
'./daemon.py'
]
]
popen_list = []
for command in commands:
popen = subprocess.Popen(command, preexec_fn=os.setsid)
popen_list.append(popen)
def stop_workers(*args, **kwargs):
for popen in popen_list:
print('send_signal', popen.pid)
popen.send_signal(signal.SIGTERM)
while True:
popen_return_code = popen.poll()
if popen_return_code is not None:
break
sleep(5)
signal.signal(signal.SIGTERM, stop_workers)
for popen in popen_list:
print('wait_main', popen.wait())
如果你运行 supervisor.py 然后在它的 pid 上调用kill -15,那么它将挂在无限循环中,因为 popen_return_code 永远不会不是 None。我发现,这基本上是因为为 wait_pid 操作添加 threading.Lock (source),但是我怎样才能重写代码以便正确处理子退出?
【问题讨论】:
标签: python python-3.x subprocess