signal
Syntax:
#include <csignal> void ( *signal( int signal, void (* func) (int)) ) (int);
The signal() function sets func to be called when signal is recieved by your program. func can be a custom signal handler, or one of these macros (defined in the csignal header file):
| Macro | Explanation |
|---|---|
| SIG_DFL | default signal handling |
| SIG_IGN | ignore the signal |
Some basic signals that you can attach a signal handler to are:
| Signal | Description |
|---|---|
| SIGTERM | Generic stop signal that can be caught. |
| SIGINT | Interrupt program, normally ctrl-c. |
| SIGQUIT | Interrupt program, similar to SIGINT. |
| SIGKILL | Stops the program. Cannot be caught. |
| SIGHUP | Reports a disconnected terminal. |
The return value of signal() is the address of the previously defined function for this signal, or SIG_ERR is there is an error.
Example code:
The following example uses the signal() function to call an arbitrary number of functions when the user aborts the program. The functions are stored in a vector, and a single "clean-up" function calls each function in that vector of functions when the program is aborted:
void f1() {
cout << "calling f1()..." << endl;
}
void f2() {
cout << "calling f2()..." << endl;
}
typedef void(*endFunc)(void);
vector<endFunc> endFuncs;
void cleanUp( int dummy ) {
for( unsigned int i = 0; i < endFuncs.size(); i++ ) {
endFunc f = endFuncs.at(i);
(*f)();
}
exit(-1);
}
int main() {
// connect various signals to our clean-up function
signal( SIGTERM, cleanUp );
signal( SIGINT, cleanUp );
signal( SIGQUIT, cleanUp );
signal( SIGHUP, cleanUp );
// add two specific clean-up functions to a list of functions
endFuncs.push_back( f1 );
endFuncs.push_back( f2 );
// loop until the user breaks
while( 1 );
return 0;
}
Related topics: