os.wait() losing child?

greg greg at cosc.canterbury.ac.nz
Wed Jul 11 04:09:31 EDT 2007


Jason Zheng wrote:
> Hate to reply to my own thread, but this is the working program that can 
> demonstrate what I posted earlier:

I've figured out what's going on. The Popen class has a
__del__ method which does a non-blocking wait of its own.
So you need to keep the Popen instance for each subprocess
alive until your wait call has cleaned it up.

The following version seems to work okay.

import os
from subprocess import Popen

pids = {}
counts = [0,0,0]
p = [None, None, None]

for i in xrange(3):
   p[i] = Popen('sleep 1', shell=True)
   pids[p[i].pid] = i
   print "Starting child process %d (%d)" % (i,p[i].pid)

while (True):
   (pid,exitstat) = os.wait()
   i = pids[pid]
   del pids[pid]
   counts[i]=counts[i]+1

   #terminate if count>10
   if (counts[i]==10):
     print "Child Process %d terminated." % i
     if reduce(lambda x,y: x and (y>=10), counts):
       break
     continue

   print "Child Process %d (%d) terminated, restarting" % (i, pid),
   p[i] = Popen('sleep 1', shell=True)
   pids[p[i].pid] = i
   print "(%d)" % p[i].pid

--
Greg



More information about the Python-list mailing list