signal.h/csignal

signal.h contains the functions to handle and raise signal events within your program. These are the common available signals that you can raise to your program:

#define    SIGINT    2   //Interactive Attention
#define    SIGILL    4   //Illegal Instruction
#define    SIGFPE    8   //Floating point error
#define    SIGSEGV  11   //Segmentation violation
#define    SIGTERM  15   //Termination request
#define    SIGBREAK 21   //Control-break
#define    SIGABRT  22   //Abnormal termination

To raise a signal to your program, use the raise(int signal) function:

#include "signal.h"
#include "stdlib.h"
int main() {
raise(SIGTERM);
system("echo This command never gets executed & pause>nul");
return 0;
}

That raised the SIGTERM signal, requesting a termination; and therefore the program terminates before the system function call.
Now there are ways to specify that you have your own custom functions to handle certain signals. To set a function to handle a signal, use the signal function. The signal function excepts 2 parameters: the first is the integer value or constant to specify which signal you are going to handle, and the second is either a pointer to a function which will handle that signal or one of the 2 constants that represent the predefined functions to handle the signal which are:

SIG_DFL	Default handling: The signal is handled by the default action for that particular signal.
SIG_IGN	Ignore Signal: The signal is ignored.

So let’s take a look at an example of handling a SIGINT signal:

#include "stdlib.h"
#include "signal.h"
void sh(int signal);
int main() {
signal(SIGINT,sh); //Associate function sh to handle SIGINT
raise(SIGINT);
return 0;
}
void sh(int signal) {
system("echo SIGINT caught! & pause");
}

Also we can choose to ignore the signal:

#include "stdlib.h"
#include "signal.h"
int main() {
signal(SIGTERM,SIG_IGN);  //SIG_INT predefined function to ignore signal.
raise(SIGTERM);           //SIGTERM = Terminate request
raise(SIGTERM);
raise(SIGTERM);
system("echo This program is still alive & pause");
return 0;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: