Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if subprocess has finished?

I am starting a process by doing:

for i in range(1, processes + 1):
            hup = MyURLParser() //A class I made
            p = Process(target = hup.run)
            p.start()

After that, so that the main thread doesn't exit immediately I do:

 while (True):
        print("Main sleeping...")
        sleep(20)

Instead of doing this, how can I check that each of the child processes are still running from the main thread ? Then instead of having the infinite loop I can break out of the loop at the right time and do something else....

like image 327
Rahul Iyer Avatar asked Jan 28 '23 19:01

Rahul Iyer


2 Answers

Add all processes to a list, and join() each of them in turn:

processes = []
for i in range(1, processes + 1):
    hup = MyURLParser() //A class I made
    p = Process(target = hup.run)
    p.start()
    processes.append(p)

for p in processes:
    p.join()

The join() call blocks until the process is finished. It doesn't matter in which order you call them; calling join() on a process that's already complete will just return immediately.

You may also want to check out the other functionality in the multiprocessing module; in particular the Pool class might help you simplify this code.

like image 198
Thomas Avatar answered Feb 07 '23 14:02

Thomas


p.is_alive() tells you whether the process is running.

To wait until it's ended, use p.join().

like image 31
grovina Avatar answered Feb 07 '23 16:02

grovina