Kill with negative numbers

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2022-05-26

You can stop a single process with kill. E.g.

kill pid # e.g. kill 808
# or kill -9 pid e.g. kill -9 808
# or kill -SIGTERM pid

But say you wanted to kill a whole process group. Then use a negative number of the process group id (and -- to offset the negative number)

kill -- -$PGID # e.g. kill -- -19701

Why might you want to do this? Basically because killing a parent process in unix does not kill children. Rather the children become orphaned and re-parented by init. In order to kill child processes, you need to kill the process group they belong to.

There is one confusing thing to be aware of: sending SIGINT (e.g. Control-C, AKA the interrupt character ^c) sends a signal to whole process group in the foreground. And, BTW, whenever you run a program in the foreground (e.g. cat or top), the shell is basically out of the way and waiting; it does nothing to facilitate your interaction with these programs (that this happens is aa common misconception). That's why your SIGINT signal does not affect your shell too. However, the shell knows to become active again because it receives SIGCHLD in its role as parent process. Note that the shell IS a parent process, but is NOT a part of the same process group. It is however, a session leader (same SID)