Execute code after death of all child processes

Mike Meyer mwm at mired.org
Fri Dec 24 07:06:50 EST 2004


mf1987 at arcor.de (Markus Franz) writes:

> 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 env_sources[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.

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

Basically, make sure that none of the children run the waitpid and
last print.

     <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list