>_ IzzyLab

Hands-on task

This task is step 14 of the course “Processes and signals”

Catch a signal with trap

medium~7 min

Write a script /root/graceful.sh that runs in an infinite loop but catches the TERM signal and, before exiting, creates a marker file /tmp/cleanup.done. That is, on receiving SIGTERM the script should shut down cleanly, leaving that file behind. The script is handy to write in the Editor tab above the terminal: create the file graceful.sh in /root and save it.

What you'll practise:
  • trap
  • signals
  • sigterm
  • bash scripts
  • graceful shutdown

Topic breakdown

Signals are the OS's way of asking a process to do something; SIGTERM is a polite request to terminate, which a program can catch in order to clean up before exiting (close files, flush buffers) — that's exactly a graceful shutdown. In bash the catch is set up with the built-in command trap: you give it handler code and a signal name. To let the script survive until the signal, it's left in an infinite wait after the handler is installed.

What's checked

  1. script created
  2. trap catches TERM and does cleanup

What it looks like