I am looking for a way to clean up the mess when my top-level script exits.
Especially if I want to use set -e
, I wish the background process would die when the script exits.
I am looking for a way to clean up the mess when my top-level script exits.
Especially if I want to use set -e
, I wish the background process would die when the script exits.
To be on the safe side I find it better to define a cleanup function and call it from trap:
or avoiding the function altogether:
Why? Because by simply using
trap 'kill $(jobs -pr)' [...]
one assumes that there will be background jobs running when the trap condition is signalled. When there are no jobs one will see the following (or similar) message:because
jobs -pr
is empty - I ended in that 'trap' (pun intended).Another option is it to have the script set itself as the process group leader, and trap a killpg on your process group on exit.
A nice version that works under Linux, BSD and MacOS X. First tries to send SIGTERM, and if it doesn't succeed, kills the process after 10 seconds.
Please note that jobs does not include grand children processes.
jobs -p does not work in all shells if called in a sub-shell, possibly unless its output is redirected into a file but not a pipe. (I assume it was originally intended for interactive use only.)
What about the following:
The call to "jobs" is needed with Debian's dash shell, which fails to update the current job ("%%") if it is missing.
Like https://stackoverflow.com/a/22644006/10082476, but with added exit-code
Just for diversity I will post variation of https://stackoverflow.com/a/2173421/102484 , because that solution leads to message "Terminated" in my environment: