Reputation: 1362
I have two child processes created by my main application process.
A = Process(target=a, args=(aaa,))
B = Process(target=b,args=())
For the sake of argument they are called A and B; How could process A terminate Process B?
Upvotes: 1
Views: 295
Reputation: 9395
Whilst I would seriously not recommend child processes being able to nuke each other. Personally I would have the main process managing child processes.
If you want to go down the route you are currently on. One way you could do what you wanted would be to get the main process to pass the process id of child A
to child B
(or how ever you want to do it). Using this the process ID you pass to the process you can then terminate the process.
Option 1:
If only one process can terminate the other then the simplest solution is for process B
to be started first. Then for process A
to be passed process B
's process ID. Using this you can the terminate the process.
def a(pid):
os.kill(pid)
B = Process(target=b, args=())
A = Process(target=a,args=(B.pid))
Option 2: To do this you can use Queues or Pipes (from the multiprocessing library).
from multiprocessing import Process, Queue
def f(q):
# will send the process id of the alternative child process
print q.get()
if __name__ == '__main__':
queue_A = Queue()
queue_B = Queue()
A = Process(target=f, args=(queue_A,))
B = Process(target=f,args=(queue_B,))
A.start()
B.start()
queue_A.put(B.pid)
queue_B.put(A.pid)
# do stuff....
Option 3 (my preferred method): Get the main process to do the terminating.
A = Process(target=a, args=())
B = Process(target=b,args=())
A.terminate()
B.terminate()
Upvotes: 2