Name

signal function — Sets a signal handler

Synopsis

void (*signal(int sig, void (*func)(int)))(int);

The signal function controls the program's behavior when a signal is delivered to the program. The first parameter (sig) is the signal number. The second parameter (func) is the function to call when signal sig is delivered.

The func parameter can also be one of the special values SIG_DFL or SIG_IGN. Use SIG_DFL to get the default behavior; use SIG_IGN to ignore a signal.

The default behavior for a signal is implementation-defined, but it usually results in the termination of the program. The signal handler must not use any C++ features (such as throwing an exception), or the results will be implementation-defined. The function must have "C" linkage.

If the func parameter is a function pointer, that function is called when signal sig is delivered. Unless the signal is delivered by calling abort or raise, the function is highly restricted in what it can do:

If the handler returns normally, and the signal is not the result of a computational error, execution continues from the point where it was interrupted.

The return value of signal is the previous value of the signal handler for sig, or SIG_ERR for an error. If SIG_ERR is returned, errno is set.

Example 13-7 shows a simple signal handler that sets a global flag when the user interrupts the program. Until the user interrupts it, the program reads input and counts the number of lines the user typed.