Say we have a test.sh
file, the content is:
$ cat test.sh
#!/usr/bin/env bash
echo "Pid: $$"
#
# catch signal #10 and do echo
trap 'echo "Caught signal user1"; exit' 10
while /bin/true ; do
sleep 5
done
You can see inside we use $$
to print out the process pid, then use trap
command to catch signal #10 then echo some messsages out.
Let's run it:
$ bash test.sh
Pid: 16195
Now let's open another terminal window, use kill
command to send #10 signal (SIGUSR1) to this pid. (BTW, if you are not familiar with kill
command, kill
doesn't mean actually kill the process, you can treat it as a "send-signal" command in this case)
$ kill -10 16195
Now in the first window you can see:
Caught signal user1
Which means we caught the #10 signal.
P.S. to see all signal numbers, use kill -l
or trap -l
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
...
Top comments (4)
Really cool tip, very useful, thanks
Bo, nice tutorial, however I don't really know the context for using this script. Could you shine a little more light on why? When? And what for?
Thanks
Hey Matt, this could be useful when you do some shell programming. For example, if your shell script will create some temporary files in order to get the task done, and once the task is done, you will clean those temporary files, the logic is something like this (psudo-code):
Now when your shell is running
do_task
part, you press Ctrl+C, your script is interrupted and stopped, but those temporary files never get cleaned up.To fix this, you can add
trap clean_temporary_files 2
to your script, which will caught theCtrl+C
signal (#2 SIGINT), then it will do theclean_temporary_files
function.Very interesting,
Thanks