How can I wait for child processes?

I have a Python script that runs tasks like this:

import os
os.system("./a.sh")
do_c()

But a.sh- this is a bash script that runs other programs. It seems that the bash script is ready before all running scripts are ready.

How can I wait until all scripts (child processes) are ready before being do_c()executed?

Clarification: when I write ready, I mean finish / exit.

Example

run.py

This file can be changed. But do not rely on sleep, since I do not know how long it takes a.pyand b.py.

#!/usr/bin/env python

import os
from time import sleep

print("Started run.py")
os.system("./a.py")
print("a is ready.")
print("Now all messages should be there.")

sleep(30)

a.py

This cannot be changed:

#!/usr/bin/env python

import subprocess
import sys

print("  Started a.py")
pid = subprocess.Popen([sys.executable, "b.py"])
print("  End of a.py")

b.py

This cannot be changed:

#!/usr/bin/env python

from time import sleep

print("    Started b.py")
sleep(10)
print("    Ended b.py")

Output required

The last message should be Now all messages should be there..

Current output

started run.py
  Started a.py
  End of a.py
a is ready.
Now all messages should be there.
    Started b.py
    Ended b.py
+4
source share
1

. a.py ( os.system ) , a.py , . PID b.py , , a.py , b.py - - PID b.py 1, init.

, , . , run.py, a.py . , , read() .

run.py, , :

#!/usr/bin/env python

import os
from time import sleep

print("Started run.py")

r, w = os.pipe()
pid = os.fork()
if pid == 0:
    os.close(r)
    os.execlp("./a.py", "./a.py")
    os._exit(127)   # unreached unless execlp fails
os.close(w)
os.waitpid(pid, 0)  # wait for a.py to finish
print("a is ready.")

os.read(r, 1)       # wait for all the children that inherited `w` to finish
os.close(r)
print("Now all messages should be there.")

:

Pipe - , . , , , , , , . ( , , stdin stdout, .)

, . , , ​​ . , , , . , , , a.py. , , , . , os.read() 0, .

:

  • os.pipe() print os.system(), , . ( - os.system() , .)

  • os.fork() , PID ( 0, PID, os.getpid()).

  • if pid == 0: execs ./a.py. "Exec" , , . os._exit() , execlp (, Python, execlp , , ). .

  • ( ). os.waitpid(pid) - a.py, os.system(). waitpid, , .

  • os.read(r, 1), : 1 . , , . a.py , - , . , os.read() , .

  • , , .

+5

Source: https://habr.com/ru/post/1532526/


All Articles