Basically I want a bash script process, upon receiving a SIGINT
, to kill all of its subprocesses before exiting. I read here to use something along the lines of:
trap "kill -TERM -$$ ; exit 1" INT QUIT
I have also read to use kill 0
:
trap "kill -TERM 0 ; exit 1" INT QUIT
What are the differences between them, and do they fulfill the following requirements (and if not, what does?)?:
./foo.sh &
and then ./foo.sh
, killing the second one shouldn't kill the first one even in the same tty).A process ID of 0 refers to the process group of the process executing the kill
command. A negative process ID refers to the process group whose ID is the absolute value of the proc ID. It's possible that the two could be different, as process groups may be changed.
They should be identical for item 1 (I'll assume you aren't manually creating or affecting process groups). Item 2 is not a concern, as process IDs are completely independent of the name of the script that executes in the process. Process IDs are the unambiguous way to refer to a specific process.
Note that it is trivial to lie about the name of the program executing in a process, so it's generally useless to rely on the name you see in ps
anyway:
exec -a someOtherName ./myScript