0

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

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
    exit(sigNum);
}

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

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

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

    while(1);

    exit(EXIT_SUCCESS);
}

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.

2

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:

#!/bin/sh

bye() {
    echo bye
    exit 1
}

trap bye SIGUSR1

echo hello

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

echo not reached

Executed:

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.