Signals are the way of communication between process but I have some questions What are signal traps? How the traps are related to signals in operating system?

2 Answers 2


Sometimes an example is worth more than a thousand words: This code in c++ exposes a very simple signal handler.

void gracefullShutdown(int sigNum) { 

    // cleanup or do wathever you need to do in case of received signal(s)

    // Terminate this executable

int main(int argc, char* argv[]) {

    signal(SIGINT , gracefullShutdown); 
    signal(SIGTERM , gracefullShutdown);

    std::cout << "starting..." << std::endl;



When you press the Ctrl+C during execution of this program, the linux kernel will send a SIGINT signal to this program, normally it would terminate, but in this precise case it leaves you the possibility to do something before terminating.


To "trap a signal" (also called install a signal handler) is do something when the signal is received. Here's a little shell script to illustrate:


bye() {
    echo bye
    exit 1

trap bye SIGUSR1

echo hello

for Y in $(jot 80)
    printf '.'
    sleep 1

echo not reached


$ shtrap & { sleep 3 && kill -s SIGUSR1 $!; }
[2] 22471
...[1]   User defined signal 1   sleep 1

We start the script as a background process, wait 3 seconds, and raise the SIGUSR1 signal with kill. The script traps that signal, and invokes its bye function.

The operating system defines default behavior for each signal. By trapping it, the program can change the default. Daemons often trap SIGHUP this way to force re-reading of a configuration file while the program is running.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .