signal()
is pretty easy to understand here's example code from the link I mentioned with my annotations:
//This is a signal handling function. When your main program gets a signal, it
// will call this function. The function just prints a message.
static void catch_function(int signal) {
printf("Interactive attention signal caught.");
}
int main(void) {
//register to catch the interrupt signal.
if (signal(SIGINT, catch_function) == SIG_ERR) {
printf("An error occurred while setting a signal handler.\n");
return EXIT_FAILURE;
}
while(1)
{
printf("do stuff\n");
sleep(1);
}
}
Now this code will loop forever (doing something), until it gets a ^C (ctrl+C) interrupt signal. At that point in time it will go do whatever it is we told it to do:
mike@linux-4puc:~> ./a.out
do stuff
do stuff
^CInteractive attention signal caught.do stuff
do stuff
do stuff
do stuff
do stuff
^CInteractive attention signal caught.do stuff
The signal function is defined as:
typedef void (*sighandler_t)(int); //this just means a pointer to a function
//that looks like: void sighandler(int)
sighandler_t signal(int signum, sighandler_t handler);
Which means:
- A pointer to a function to handle a signal can be referred to "sighandler_t"
- A function that meets the sighandler_t type needs to return nothing, and take an int
- The signal function then takes the parameters of the signal type to catch, and a function meeting the "sighandler_t" typedef.
Then at a system level, when our program is running, if a signal comes in and we have handling for it, we do so, if we don't have handling in place, the OS takes a default action.
If you remove the signal call from my above example, you'll see ctrl+C now kills the program instead of just allowing the signal handler to run.
Answer your question?