C++ signal processing
A signal is an interrupt passed to the process by the operating system and terminates a program early. On UNIX, LINUX, Mac OS X, or Windows systems, you can generate an interrupt by pressing Ctrl+C.
Some signals cannot be captured by the program, but the signals listed in the table below can be captured in the program and can take appropriate action based on the signal. These signals are defined in the C++ header file <csignal> in.
|SIGABRT||Abnormal termination of the program, such as calling abort.|
|SIGFPE||Incorrect arithmetic operations, such as division by zero or an operation that causes an overflow.|
|SIGILL||Detects illegal instructions.|
|SIGINT||Received an interactive attention signal.|
|SIGSEGV||Illegal access to memory.|
|SIGTERM||A termination request sent to the program.|
The C++ Signal Processing Library provides a signal function to capture incidents. Here is the syntax for the signal() function:
void (* Span>signal (int sig , void (*func)(int)))(int);
This function takes two arguments: the first argument is an integer representing the number of the signal; the second argument is a pointer to the signal handler.
Let's write a simple C++ program that uses the signal() function to capture the SIGINT signal. Regardless of what signal you want to capture in your program, you must use the signal function to register the signal and associate it with the signal handler. Take a look at the example below:
When the above code is compiled and executed, it produces the following results:
Going to sleep.. .. Going to sleep.... Going to sleep....
Now, press Ctrl+C to interrupt the program, you will see the program capture signal, the program prints the following and exits：
Going to sleep.... Going to sleep.... Going to sleep.... Interrupt signal (2) received.
You can use the function raise() to generate a signal with an integer signal number as a parameter, the syntax is as follows:
int raise (signal sig);
Here, sig is the number of the signal to be sent, including: SIGINT, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM, SIGHUP. Here's an example of how we generate signals internally using the raise() function:
When the above code is compiled and executed, it will produce the following results and will automatically exit:
Going to sleep.. .. Going to sleep.... Going to sleep.... Interrupt signal (2)accepted.< !-- Other extensions -->