简体   繁体   中英

Python Multiprocessing: How to close parent if child closes?

how do I close the parent process if any of the child processes exit?

if __name__ == "__main__":

    p1 = multiprocessing.Process(target=startFlaskServer)
    p2 = multiprocessing.Process(target=startWebview)

    p1.start()
    time.sleep(2)
    p2.start()

Please note that the time.sleep(2) is required to allow the flask web server to load before the gui wrapper. How to I edit my script so that when the user closes the gui window (p2), the flask web server (p1) also exits?

Thanks!

This isn't the right way to do this. You should use any suitable means of interprocess communication (eg. pipes) to know when the 'startFlaskSever' is completed and then start the 'startWebView'. What if something in the p1 takes longer than 2 seconds?

The same communication mechanism should be used to close any process based on any other process's state.

Read more here: https://docs.python.org/3/library/multiprocessing.html https://docs.python.org/3/library/ipc.html https://pymotw.com/3/multiprocessing/communication.html

At the end of your code join the GUI process. This will wait for the process to end. The use a method to close the other process. In many cases terminate() should do the deal:

 p2.join()
 p1.terminate()

More stubborn processes might need a .kill() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM