os.wait() losing child?
Jason Zheng
Xin.Zheng at jpl.nasa.gov
Fri Jul 13 19:52:09 EDT 2007
Hrvoje Niksic wrote:
> Jason Zheng <Xin.Zheng at jpl.nasa.gov> writes:
>> I'm concerned about portability of my code. It will be run on
>> multiple machines with mixed Python 2.4 and 2.5 environments.
>
> I don't think there is a really clean way to handle this.
I think the following might just work, albeit not "clean":
#!/usr/bin/python
import os,subprocess
from subprocess import Popen
pids = {}
counts = [0,0,0]
def launch(i):
p = Popen('sleep 1', shell=True, cwd='/home',
stdout=file(os.devnull,'w'))
pids[p.pid] = p, i
if p in subprocess._active:
subprocess._active.remove(p)
print "Starting child process %d (%d)" % (i,p.pid)
for i in xrange(3):
launch(i)
while (True):
pid, ignored = os.wait()
try:
p, i = pids[pid]
except KeyError:
# not one of ours
continue
del pids[pid]
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 terminated, restarting" % i
launch(i)
More information about the Python-list
mailing list