Pages

Thursday, June 02, 2005

UNIX: Writing a Signal Handler

What is a signal?

A signal is a software interrupt, sent to a process to notify that an event has occured. Signals are usually sent by the Operating System (kernel) to notify processes that some event has occurred. Due to this, the processes need not poll for a particular event. By their nature, signals interrupt whatever the process is doing at that moment, and force it to handle them immediately. Because events may occur asynchronously, it is a good practice for the process to handle all the relevant signals using the API provided by the OS.

For example, the user may want to stop the process any time by pressing Control-C, which results in SIGINT signal.

Each signal has an integer number, as well as a symbolic name associated with it. Usually these are defined in /usr/include/sys/iso/signal_iso.h header file on Solaris. Note that we have to include /usr/include/signal.h file in our C/C++ programs, if we are going to use the signal API.

There are about 25 different kinds of signals, depending on the flavor of the system. Use the command kill -l, to get the list of signals supported by your system.

%uname -a
SunOS Govinda 5.9 Generic_118558-02 sun4u sparc SUNW,Ultra-Enterprise

% kill -l
HUP INT QUIT ILL TRAP ABRT EMT FPE
KILL BUS SEGV SYS PIPE ALRM TERM USR1
USR2 CLD PWR WINCH URG POLL STOP TSTP
CONT TTIN TTOU VTALRM PROF XCPU XFSZ WAITING
LWP FREEZE THAW CANCEL LOST XRES RTMIN RTMIN+1
RTMIN+2 RTMIN+3 RTMAX-3 RTMAX-2 RTMAX-1 RTMAX

For some signals, the default behavior is to ignore the signal. For others, the default behavior is to terminate the process.

Some terminating signals also produce the image of the memory layout (aka core) of the process when it was terminated. The core file will be useful for debugging. On Solaris, the behavior of all the signals was documented in /usr/include/sys/iso/signal_iso.h file.

The process can catch most of the signals except for a few. The process cannot catch SIGKILL & SIGSTOP signals. When the process receives such signals, it will be terminated.

If the program does not install any signal handlers, the run-time environment sets up a set of default signal handlers for the program. For example, the default signal handler for the TERM signal calls the exit() system call. The default handler for the ABRT is to dump the process's memory image into a file named core in the process's current directory, and then exit.

The signal handler is a function that gets called when the process receives a signal. The function is called in asynchronous mode, meaning that no where in the program you have code that calls this function directly. Instead, when the signal is sent to the process, the OS stops the execution of the process, and forces it to call the signal handler function. When the signal handler function returns, the process continues execution from wherever it happened to be before the signal was received. Failing to properly handle various signals, would likely cause our application to terminate, when it receives such signals.

The process can install its own signal handler to change the default behavior of any signal, except for SIGTERM.

Examples

Sending signals
---------------

Signals can be sent using keyboard (Ctrl-C, Ctrl-Z etc.,), command line with kill -<signal> <PID> (eg., kill -9 1234, kills the process with PID 1234) or using system calls.

The following C program shows how to send signals with kill() system call

% cat sendsignal.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>

int main() {
pid_t my_pid = getpid();
printf("\nMy process id (PID) = %d. Killing myself ..", my_pid);
kill(my_pid, SIGKILL);
return (0);
}

% cc -o sendsignal sendsignal.c
% ./sendsignal

My process id (PID) = 15031. Killing myself ..Killed


Simple signal handler
---------------------
The following trivial C program illustrates, how to write a simple signal handler

% cat signalhandler.c
#include <stdio.h>
#include <unistd.h>
#include <signal.h>

/*
* signal handler
*/

void CatchInterrupt (int signum) {
pid_t my_pid;

printf("\nReceived an interrupt! About to exit ..\n");
fflush(stdout);
my_pid = getpid();
kill(my_pid, SIGKILL);
}

int main(int argc, char** argv) {
/*
* Set the INT (Ctrl-C) signal handler to 'CatchInterrupt'
*/
signal(SIGINT, CatchInterrupt);

/*
* Do Nothing and wait for interrupts
*/
for ( ;; ) {}
}

% cc -o signalhandler signalhandler.c

% ./signalhandler
^C
Received an interrupt! About to exit ..
Killed

In the above program, the process simply waits in an infinite loop, for an interrupt event to occur and as soon as it receive one, it exits after printing a message on the console.

Note:
If the process should not die, and has to handle the signal whenever the event occurs, we have to reset (reinstall) the signal handler in CatchInterrupt() for it to catch the interrupt signals further. The modified code will be like this:

/*
* signal handler
*/

void CatchInterrupt (int signum) {
/*
* Reset the signal handler to catch interrupt again
*/
signal(SIGINT, CatchInterrupt);
printf("\nReceived an interrupt! Waiting for further interrupt signals ..\n");
fflush(stdout);
}

The behavior will be like this, after compiling and executing the code:

%./signalhandler
^C
Received an interrupt! Waiting for further interrupt signals ..
^C
Received an interrupt! Waiting for further interrupt signals ..
^C
Received an interrupt! Waiting for further interrupt signals ..
^C
Received an interrupt! Waiting for further interrupt signals ..
^Z
Stopped (user)


Reference:
Introduction To Unix Signals Programming

Technorati tag:

2 comments:

  1. thanks it helped in my assignment. simple and concise explanation

    ReplyDelete
  2. Unfortunately, while your example may work as an exercise, it will cause problems in real programs. Neither printf, nor fflush are async-safe, which means they cannot be safely invoked from within a signal handler. The results are undefined, and I have seen programs locking up because of this. Just an FYI.

    ReplyDelete