C Library Function - signal()
C Standard Library - <signal.h>
Description
The C library function void (signal(int sig, void (func)(int)))(int) sets a function to handle a signal, i.e., a signal handler with the sig parameter.
Declaration
Here is the declaration for the signal() function.
void (*signal(int sig, void (*func)(int)))(int)
Parameters
- sig -- The signal code used as a variable in the signal handler. Below are some important standard signal constants:
| Macro | Signal |
|---|---|
| SIGABRT | (Signal Abort) Abnormal termination of the program. |
| SIGFPE | (Signal Floating-Point Exception) Arithmetic operation error, such as division by zero or overflow (not necessarily floating-point operations). |
| SIGILL | (Signal Illegal Instruction) Illegal function image, such as an illegal instruction, usually due to a variant in the code or an attempt to execute data. |
| SIGINT | (Signal Interrupt) Interrupt signal, such as ctrl-C, usually generated by the user. |
| SIGSEGV | (Signal Segmentation Violation) Illegal memory access, such as accessing a non-existent memory unit. |
| SIGTERM | (Signal Terminate) Termination request signal sent to the program. |
- func -- A pointer to a function. It can be a function defined by the program or one of the following predefined functions:
| SIG_DFL | Default signal handler. | | SIG_IGN | Ignore the signal. |
Return Value
The function returns the previous value of the signal handler, or SIG_ERR on error.
Example
The following example demonstrates the use of the signal() function.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
void sighandler(int);
int main()
{
signal(SIGINT, sighandler);
while(1)
{
printf("Sleeping for one second...\n");
sleep(1);
}
return(0);
}
void sighandler(int signum)
{
printf("Caught signal %d, exiting...\n", signum);
exit(1);
}
Let's compile and run the above program, which will produce the following result and enter an infinite loop, requiring the use of CTRL + C to exit the program.
Sleeping for one second...
Sleeping for one second...
Sleeping for one second...
Sleeping for one second...
Sleeping for one second...
Caught signal 2, exiting...