Signals are software interrupts i.e. ctrl+c ctrl+z etc.
By hitting ctrl+c or somethign similar, a process sends a signal to kill another process etc are all such cases where a process needs to do signal handling. So in summary a robust program need to handle signals because signal deliver asynchronous events to the application.
List of Signals
Signal Value Action Comment
SIGHUP 1 Term Hangup detected on controlling terminal
or death of controlling process
SIGINT 2 Term Interrupt from keyboard
SIGQUIT 3 Core Quit from keyboard
SIGILL 4 Core Illegal Instruction
SIGABRT 6 Core Abort signal from abort(3)
SIGFPE 8 Core Floating point exception
SIGKILL 9 Term Kill signal
SIGSEGV 11 Core Invalid memory reference
SIGPIPE 13 Term Broken pipe: write to pipe with no readers
SIGALRM 14 Term Timer signal from alarm(2)
SIGTERM 15 Term Termination signal
SIGUSR1 30,10,16 Term User-defined signal 1
SIGUSR2 31,12,17 Term User-defined signal 2
SIGCHLD 20,17,18 Ign Child stopped or terminated
SIGCONT 19,18,25 Continue if stopped
SIGSTOP 17,19,23 Stop Stop process
SIGTSTP 18,20,24 Stop Stop typed at tty
SIGTTIN 21,21,26 Stop tty input for background process
SIGTTOU 22,22,27 Stop tty output for background process
Note: SIGKILL and SIGSTOP can not be trapped
Trapping a Signal in C
If a process wishes to handle a certain signal(s), the process has to register a signal handling function to the kernel.
void (*signal(int signo, void (*func )(int)))(int);
The signal handler function has void return type and accepts a signal number corresponding to the signal that needs to be handled.
To get the signal handler function registered to the kernel, the signal handler function pointer is passed as second argument to the ‘signal’ function.
// Define the function to be called when ctrl-c (SIGINT) signal is sent to process
printf("Caught signal %d\n",signum);
// Your Code
// Registering signal
if (signal(SIGINT, sig_handler) == SIG_ERR)
printf("\ncan't catch SIGINT\n");
Important Point while Handling the Signal
1. Signal Catching Functions should be Reentrant to avoid the signal generation by the different thread when one thread is handling the signal.
2. There may be a need to different signal handling behavior for different thread i.e. For example, a thread A can choose to ignore a particular signal but a thread B can choose to catch the same signal. In this case the request made by thread A gets overruled by thread B’s request as signals are delivered only to a single thread in any process. (exception: hardware exceptions or the timer expiry). Use posix APIs like pthread_sigmask() to counter this shortcoming.
Comments are welcome