C Library Function - signal()
Description
C Library Function **void (signal(int sig, void (func)(int)))(int) Sets a function to handle a signal, that is, a signal handler with sig parameter.
signal The function is a function in the C standard library, used to set a signal handler. This function is defined in header.signal The function allows a program to define the handler to execute 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 used as a variable in the signal handler. Below are some important standard signal constants:
| macro | Signal |
|---|---|
| SIGABRT | (Signal Abort) Abnormal program termination. |
| 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 caused by some variation in the code or an attempt to execute data. |
| SIGINT | (Signal Interrupt) Interrupt signal, such as ctrl-C, typically generated by the user. |
| SIGSEGV | (Signal Segmentation Violation) Illegal memory access, such as accessing a nonexistent memory location. |
| SIGTERM | (Signal Terminate) A 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 | The default signal handler. |
|---|---|
| SIG_IGN | Ignore the signal. |
Return Value
This function returns the previous value of the signal handler, and returns SIG_ERR when an error occurs.
Example
The following example demonstrates the use 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
(
"Signal %d caught, jumping out...\n"
,
signum
)
;
exit
(
1
)
;
}
Let us compile and run the above program, which will produce the following result, and the program will enter an infinite loop; you need to press CTRL + C to jump out of the program.
开始休眠一秒钟...
开始休眠一秒钟...
开始休眠一秒钟...
开始休眠一秒钟...
开始休眠一秒钟...
捕获信号 2,跳出...
C Standard Library -