How to use Popen to run backgroud process and avoid zombie?

百般思念 提交于 2019-12-22 09:10:13

问题


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.

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?

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

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

回答1:


If you add a signal handler for SIGCHLD you will have the kernel handle the wait/reap piece.

Specifically the line:

signal.signal(signal.SIGCHLD, signal.SIG_IGN)

Will take care of your Zombies.



来源:https://stackoverflow.com/questions/6442428/how-to-use-popen-to-run-backgroud-process-and-avoid-zombie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!