Running the below code and then doing Ctrl+C
can leave p1
, p2
, p3
and p4
running in the background (where Ctrl+C
does nothing).
How to use KeyboardInterrupt
from the main process such that it also stops all child processes?
import time
from multiprocessing import Process
def process(proc_n):
while True:
try:
pass
except KeyboardInterrupt:
break
except Exception as e:
print(e)
time.sleep(0.5)
def main():
p1 = Process(target=process, args=(1,))
p2 = Process(target=process, args=(2,))
p3 = Process(target=process, args=(3,))
p4 = Process(target=process, args=(4,))
p1.start()
p2.start()
p3.start()
p4.start()
if __name__ == '__main__':
main()