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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Markus Franz

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

    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
  • Jeff Epler

    #2
    Re: Execute code after death of all child processes - (correctedposti ng)

    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)

    iD8DBQFBzXcmJd0 1MZaTXX0RAjtXAK CV0GZ7o3GW3bJ0p BRdgH+CyLcjAgCe J2cO
    Op+TNBqmhANGSEh IUYAq6eE=
    =O4tl
    -----END PGP SIGNATURE-----

    Comment

    Working...