use trap 'kill 0' EXIT
in the main script. that will kill all children upon script exit. regardless how script exit. except kill -9
. more on that later.
to demonstrate i created two files
$ cat killchildren
#! /bin/sh
trap 'echo killing all children; kill 0' EXIT # this is the important line
./sleepx 4 &
./sleepx 2
echo killchildren done
$ cat sleepx
#! /bin/sh
trap 'echo sleep$1 killed' EXIT # just print that it was killed
sleep $1
trap - EXIT # clear trap so not print that it was killed
echo sleep$1 done
here it is just run and left alone
$ ./killchildren
sleep2 done
killchildren done
killing all children
sleep4 killed
here it is killed with normal kill
(note i raised the sleep times because i am not fast typer)
$ ./killchildren &
[1] 13248
$ kill 13248
killing all children
sleep8 killed
sleep10 killed
[1]+ Terminated ./killchildren
here it is killed with kill -9
$ ./killchildren &
[1] 13259
$ kill -9 13259
[1]+ Killed ./killchildren
$ # ... time passes ...
sleep8 done
sleep10 done
note that there was no exit message from the main script and the children were not killed.
not tested much. works at least with sh on arch linux as of 2018.
it will not work if main script is kill -9
. because the semantic of kill -9
is to terminate immediately without letting process do anything. not even trap handling.
that said whatever kills your process should not do it with kill -9
. i would consider that a bug. here is more information on why not kill -9
:
kill -9
?Can the thing doing the killing be changed, in particular to specify a process group rather than a process?
– icarus Dec 24 '18 at 15:37