signal function — Sets a signal handler
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:
The handler must not call any function in the standard
library except signal
, and
the first parameter must be sig
.
The handler must not refer to any variable with static
storage except it can assign a value to a variable of type
volatile
sig_atomic_t
.
If the signal is the result of a computational error such
as SIGFPE
, the signal handler
must not return, but should call abort
or exit
. (Yes, this item contradicts the
first item.)
Real implementations have looser restrictions, such as
allowing calls to other library functions from a signal handler.
The library functions that are permitted varies, but every
practical implementation allows at least abort
. If you must use signal handlers
in your program, you will probably need to rely on behavior that
is dictated by your host environment, extending the limitations of
the C++ standard.
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.
Example 13-7. Reading input until the program is interrupted
#include <csignal> #include <iostream> #include <string> volatile std::sig_atomic_t interrupted; // Signal handler sets a global flag extern "C" void sigint(int sig) { interrupted = 1; } int main( ) { // if (std::signal(SIGINT, sigint) == SIG_ERR) std::cerr << "Cannot set signal handler\n"; else { unsigned long count = 0; // Count lines. while(! interrupted) { std::cout << "> "; // User prompt std::string s; if (! std::getline(std::cin, s)) // EOF does not terminate the loop; only SIGINT does this. std::cin.clear( ); ++count; } std::cout << "I counted " << count << " line(s).\n"; } }