C Function Signal
# C Library Function - signal()
[ C Standard Library - ](#)
## Description
The C library function **void (*signal(int sig, void (*func)(int)))(int)** sets a function to handle the signal, i.e., a signal handler with the **sig** parameter.
The `signal` function is a function in the C standard library used to set a signal handler. This function is defined in the `` header file. The `signal` function allows a program to define a handler to be executed when certain signals (such as `SIGINT`, generated by pressing Ctrl+C) arrive.
## Declaration
Below is the declaration of the signal() function.
void (*signal(int sig, void (*func)(int)))(int);
## Parameters
* **sig** -- The signal code to be 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 error, such as division by zero or overflow (not necessarily a floating-point operation). |
| SIGILL | (Signal Illegal Instruction) Illegal function image, such as an illegal instruction, usually due to a corruption 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 access to storage, such as accessing a non-existent memory unit. |
| SIGTERM | (Signal Terminate) Termination request signal sent to this 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
This function returns the previous value of the signal handler, or SIG_ERR if an error occurs.
## Example
The following example demonstrates the usage of the signal() function.
## Example
#include
#include
#include
#include
void sighandler(int);
int main()
{
signal(SIGINT, sighandler);
while(1)
{
printf("Start sleeping for one second...n");
sleep(1);
}
return(0);
}
void sighandler(int signum)
{
printf("Caught signal %d, exiting...n", signum);
exit(1);
}
Let us compile and run the above program, this will produce the following result, and the program will enter an infinite loop, requiring the CTRL + C key to exit the program.
Start sleeping for one second...Start sleeping for one second...Start sleeping for one second...Start sleeping for one second...Start sleeping for one second...Caught signal 2, exiting...
[ C Standard Library - ](#)
YouTip