The signal() function defined in the signal.h header file. It helps to handle the signals with a signal numbers.
void (*signal(int sig, void (*func)(int)))(int); #where sig should be in integer
The signal() function takes a signal number and a function as its parameter. Some important standard signal numbers are.
Following are the predefined functions
Parameter | Description | Required / Optional |
---|---|---|
sig | the signal number to which a handling function is set. | Required |
func | This is a pointer to a function. This can be a function defined by the programmer | Required |
The signal() function returns the previous signal handler value or SIG_ERR on error.
Input | Return Value |
---|---|
if parameters | value of the signal handler |
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
int main () {
signal(SIGINT, handler);
while(1) {
printf("Going to sleep for a second...\n");
sleep(1);
}
return(0);
}
void handler(int SNo) {
printf("Caught signal %d, coming out...\n", SNo);
exit(1);
}
Output:
Going to sleep for a second... Going to sleep for a second... Going to sleep for a second... Going to sleep for a second... Going to sleep for a second... Caught signal 2, coming out...
#include <stdio.h>
#include <signal.h>
int main()
{
signal(SIGINT, handle_sigint);
while (1)
{
printf(“signal processing\n”);
sleep(1);
}
return 0;
}
Output:
signal processing signal processing signal processing terminated