DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Bo
Bo

Posted on

Use `trap` to catch signals - Linux Tips

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Now in the first window you can see:

Caught signal user1
Enter fullscreen mode Exit fullscreen mode

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
...
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
raagpc profile image
raag pc

Really cool tip, very useful, thanks

Collapse
 
mccurcio profile image
Matt Curcio • Edited on

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

Collapse
 
0xbf profile image
Bo Author

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):

prepare_temporary_files()
do_task() # may take a long time
clean_temporary_files()

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 the Ctrl+C signal (#2 SIGINT), then it will do the clean_temporary_files function.

Collapse
 
mccurcio profile image
Matt Curcio

Very interesting,
Thanks

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.