如何使用Popen运行后台进程并避免僵尸? [英] How to use Popen to run backgroud process and avoid zombie?
问题描述
我有一个为每个客户端处理程序运行新线程的侦听器服务器.每个处理程序都可以使用:
I've a listener server running new thread to for each client handler. Each handler can use:
proc = subprocess.Popen(argv, executable = "./Main.py", stdout = _stdout, stderr = subprocess.STDOUT, close_fds=False)
在处理程序线程结束之后,在后台运行新进程.
to run new process in background, after what the handler thread is ended.
后台进程结束后,保持在Z状态.是否有可能要求subprocess.Popen()处理SIG_CHILD以避免这种僵尸?
After the background process is ended, it is kept in Z state. Is it possible to ask subprocess.Popen() to handle SIG_CHILD to avoid this zombie?
我不想使用proc.wait()来读取进程状态,因为为此,我必须保存所有正在运行的后台进程的列表...
I don't want to read process state using proc.wait(), since for this I've to save the list of all running background processes...
UPD
我需要在后台运行某些进程以避免僵尸,并使用.communicate()运行某些进程以从这些进程读取数据.在那种情况下,使用 koblas 的信号技巧,我会收到一个错误:
I need to run some processes in background avoiding zombies and to run some processes with .communicate() to read data from these processes. In that case using signal trick from koblas I get an error:
File "./PyZWServer.py", line 115, in IsRunning
return (subprocess.Popen(["pgrep", "-c", "-x", name], stdout=subprocess.PIPE).communicate()[0] == "0")
File "/usr/lib/python2.6/subprocess.py", line 698, in communicate
self.wait()
File "/usr/lib/python2.6/subprocess.py", line 1170, in wait
pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
File "/usr/lib/python2.6/subprocess.py", line 465, in _eintr_retry_call
return func(*args)
OSError: [Errno 10] No child processes
Error happened during handling of client
推荐答案
如果为SIGCHLD添加信号处理程序,则将由内核来处理等待/收获部分.
If you add a signal handler for SIGCHLD you will have the kernel handle the wait/reap piece.
特别是这行:
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
会照顾好你的僵尸.
这篇关于如何使用Popen运行后台进程并避免僵尸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!