Terminate all functions after one of them ends - Python Multiprocessing

Viewed 32

I do have a program that runs 2 functions at the same time in different Shell windows.

How can I stop all functions running if one of them finish the execution?

'''

import multiprocessing
import subprocess

def startp1():
    subprocess.call('python teste.py', creationflags=subprocess.CREATE_NEW_CONSOLE)

def startp2():
    subprocess.call('python teste2.py', creationflags=subprocess.CREATE_NEW_CONSOLE)

if __name__ == '__main__':

    p1 = multiprocessing.Process(target=startp1)
    p2 = multiprocessing.Process(target=startp2)
    p1.start()
    p2.start()

'''

1 Answers

Your code as it looks right now doesn't make much sense. subprocess.call starts a new process. So why are you using multiprocessing.Process too? I would suggest using Popen, and when one of your processes is done, using terminate in the other process.

For example:

p1 = subprocess.Popen(["dmesg"], stdout=PIPE)
p2 =subprocess.Popen(["sleep 10"], stdout=PIPE)
while True:
   if p1.poll() is not None:
     # p1 has finished.
     p2.terminate()
     break
   if p2.poll() is not None:
     # p2 has finished
     p1.terminate()
     break
Related