Execute code after death of all child processes - (corrected posting)

M

Markus Franz

Hallo!


I have a problem with this little script written in Python:


import sys, os, time
texts = ['this is text1', 'this is text 2']
for current_text in env_sources[0:]:
pid = os.fork()
if pid == 0:
time.sleep(2)
print current_text
break

As you is create some child processes depending on the number of vars
in ?texts?. My problem is: How can I run some code after all child
processes have been finished? (The code should be run only in the
parent process.)

I tried:

import sys, os, time
texts = ['this is text1', 'this is text 2']
for current_text in texts[0:]:
pid = os.fork()
if pid == 0:
time.sleep(2)
print current_text
break
os.waitpid(-1, 0)
print 'this is the end'

But this didn't work, 'this is the end' will be showed several times.

Can you help me?

Tanks.


Markus
 
J

Jeff Epler

First, you'll want to exit from each forked copy, or else it will reach
the code-after-the-for-loop:
import sys, os, time
texts = ['this is text1', 'this is text 2']
for current_text in texts[0:]:
pid = os.fork()
if pid == 0:
time.sleep(2)
print current_text
raise SystemExit

Next, you'll want to wait for each process you started:
for current_text in texts:
os.waitpid(-1, 0)
print 'this is the end'


$ python /tmp/franz.py
this is text1
this is text 2
this is the end

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.6 (GNU/Linux)

iD8DBQFBzXcmJd01MZaTXX0RAjtXAKCV0GZ7o3GW3bJ0pBRdgH+CyLcjAgCeJ2cO
Op+TNBqmhANGSEhIUYAq6eE=
=O4tl
-----END PGP SIGNATURE-----
 
D

Denis S. Otkidach

Next, you'll want to wait for each process you started:
for current_text in texts:
os.waitpid(-1, 0)
print 'this is the end'

This can eventually die with exception. The proper way is:

try:
while True:
os.waitpid(-1, 0)
except OSError, exc:
if exc.errno!=errno.ECHILD:
raise
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top