I am unable to trap a signal when running in a child / background process.
Here is my simple bash script:
#!/bin/bash
echo "in child"
trap "got_signal" SIGINT
function got_signal {
echo "trapped"
exit 0
}
while [ true ]; do
sleep 2
done
When running this and later do
kill -SIGINT (pid)
everything works as expected, it prints trapped and exits.
Now, if I start the same script from a parent script like this:
#!/bin/bash
echo "starting the child"
./child.sh &
Then the child does not trap the signal anymore…. ?
After changing to use SIGTERM instead of SIGINT, it seems to be working correctly… ?
The
bashmanpage on OSX (but it should be the same in other versions) has this to say about signal handling:and further on, under the
trapcommand:Since scripts don’t use job control by default, this means the case you’re talking about.