The signal() Function
C++ signal-handling library provides function signal to
trap unexpected events. Following is the syntax of the
signal() function:
void (*signal (int sig, void (*func)(int)))(int);
Keeping it simple, this function receives two arguments: first
argument as an integer, which represents signal number and second
argument as a pointer to the signal-handling function.
36. SIGNAL HANDLING
#include <iostream>
#include <csignal>
using namespace std;
void signalHandler( int signum )
{
cout << "Interrupt signal (" << signum << ") received.\n";
// cleanup and close up stuff here
// terminate program
exit(signum);
}
int main ()
{
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);
while(1){
cout << "Going to sleep...." << endl;
sleep(1);
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Going to sleep....
Going to sleep....
Going to sleep....
Now, press Ctrl+C to interrupt the program and you will see
that your program will catch the signal and would come out by printing something as follows:
Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.
No comments:
Post a Comment