Reputation: 4571
If I kill a Python process via Ctrl-C
, all child processes (started by subprocess
) die. However, if I kill the Python process via kill -2
, the child processes keep running. I thought that Ctrl-C
was the same as sending a SIGINT
(i.e., kill -2
). Why is the behavior different?
Upvotes: 5
Views: 992
Reputation: 2488
The python process, and its children started by multi-process or subprocess, are all attached to the same terminal -- specifically, they are all part of the same process group. When the terminal receives the Ctrl-C, it will send SIGINT to all processes attached to the terminal, which is why you see the main python thread and its children receive the signal.
When you do kill -2 PID
you are sending the SIGINT to a specific process of that process group; other processes will not be selected.
If instead you do kill -2 -PGID
(notice the minus sign, and the G
), you replicate the action of Ctrl-C. This instructs kill to target the signal at the process group level; all processes within the group will receive the signal.
You can run this command to see the process group ID for each of your python processes:
ps -o pgid,ppid,pid,lwp,sgi_p,fname,cmd -C python
... example output ....
PGID PPID PID LWP P COMMAND CMD
22706 19662 22706 22706 * python python parent.py
22706 22706 22707 22707 * python python /var/tmp/child.py
22706 22706 22708 22708 * python python /var/tmp/child.py
22706 22706 22709 22709 * python python /var/tmp/child.py
22706 22706 22710 22710 * python python /var/tmp/child.py
22706 22706 22711 22711 * python python /var/tmp/child.py
(PGID: group ID, PPID: parent ID, PID: process ID, LWP: thread ID)
... then to send SIGINT to the entire group:
kill -2 -22706
See here for good explanation of Ctrl-C and process groups: https://unix.stackexchange.com/questions/149741/why-is-sigint-not-propagated-to-child-process-when-sent-to-its-parent-process
Upvotes: 6