How to use Popen to run backgroud process and avoi

2019-05-04 00:07发布

问题:

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.