C++ Signal Handling
There are signals which cannot be caught by the program but there is a following list of signals which you can catch in your program and can take appropriate actions based on the signal.
These signals are defined in <csingnal> header file.
Here are the list of signals along with their description and working capability:
The signal() Function
C++ signal-handling library provides function signal to trap unexpected interrupts or events.
This function is set to handle the signal.
It specifies a way to handle the signals number specified by sig.
Parameter func specifies one of the three ways in which a signal can be handled by a program.
We must keep in mind that the signal that we would like to catch must be registered using a signal function and it must be associated with a signal handling function.
Note: The signal handling function should be of the void type.
The return type of this function is the same as the type of parameter func.
If the request of this function is successful, the function returns a pointer to the particular handler function which was in charge of handling this signal before the call, if any.
Data race is undefined. If you call this function in a multi- threaded program then it will cause undefined behavior.
This function never throws exception.
Let's see a simple example to demonstrate the use of signal() function:
Signal is handled
Let's see another simple example:
SignalValue: 0 Sending signal 2 SignalValue: 2
The raise() Function
The C++ signal raise() function is used to send signals to the current executing program.
<csignal> header file declared the function raise() to handle a particular signal.
sig: The signal number to be sent for handling. It can take one of the following values:
On success, it returns 0 and on failure, a non-zero is returned.
Concurrently calling this function is safe, causing no data races.
This function never throws exceptions, if no function handlers have been defined with signal to handle the raised signal.
Let's see a simple example to illustrate the use of raise() function when SIGABRT is passed:
Before signal handler is called Signal = 0 After signal handler is called Signal = 6
Let's see a simple example to illustrate the use of raise() function when SIGINT is passed:
Before called Signal = 0 After called Signal = 2
Let's see a simple example to illustrate the use of raise() function when SIGTERM is passed:
Before called Signal = 0 After called Signal = 15
Let's see a simple example to illustrate the use of raise() function when SIGSEGV is passed:
Before called Signal = 0 After called Signal = 11
Let's see a simple example to illustrate the use of raise() function when SIGFPE is passed:
Before called Signal = 0 After called Signal = 8