I have this line:
trap 'jobs -p | xargs kill -9' SIGINT SIGTERM EXIT
it is repeated in many bash shell scripts I have.
What is the best way to share this code? Can I call a bash function perhaps?
In reality, I am creating a framework and the user will be expected to write some glue shell scripts. What would be nice if the user's shell scripts could inherit from a base shell script, somehow. Or they could just call bash functions that pre-exist somehow.
The problem is that if I create a bash function like so:
// a.sh
function trap_and_kill_child_jobs {
trap 'jobs -p | xargs kill -9' SIGINT SIGTERM EXIT
}
and call it from another script like so:
// b.sh
source ./a.sh
trap_and_kill_child_jobs
sh -c 'sleep 10000 &' & # I want this process to be killed by `trap_and_kill_child_jobs`
./run-some-tests.js
the caller script (b.sh
) does not actually experience the trap. The 'child jobs' created by b.sh will continue running.
trap_and_kill_child_jobs
function wouldn't invoke trap to actually work? – Alexander Mills Sep 06 '17 at 19:44node
works. I'm not a JS developer, but I expect what's going on is thatnode
is forking and starting some other processes, and then exiting. So it won't show up in your "jobs" list at all. Again, a shell scripting framework is almost invariably code smell. You have architectural problems here; you're trying to use the shell to keep track of internal workings of JS when it really can't do that. – Wildcard Sep 06 '17 at 20:12node server.js
is just starting a server that will listen on a port, the process will be kept alive indefinitely until it receives a signal. To elaborate, callingtrap_and_kill_child_jobs
works if the function is declared the same script, but not if the function is sourced from another script. By "works" I mean the nodejs server is killed by trap when the process that executed the bash script exits. – Alexander Mills Sep 06 '17 at 20:14trap
command really does work differently in functions. Try using thesleep
command and perhapssh -c 'sleep 10000 &'
and so forth to get some jobs to start other processes. See if you can make the sleep commands get killed/not get killed. Again, see the fundamental philosophy of debugging—make it possible for someone else to look at the same phenomena you see. – Wildcard Sep 06 '17 at 20:37node server.js
command for the sleep command you mentioned. – Alexander Mills Sep 06 '17 at 20:58trap
doesn't operate correctly/the same when run in a function sourced from another file (which I doubt is actually the case), it will be possible to reproduce this behavior without node.js at all, using only standard shell commands. – Wildcard Sep 06 '17 at 21:02sh
instead ofnode
in the example – Alexander Mills Sep 06 '17 at 21:04