Jtti: How to use the signal() function in Linux

signal() function

I accidentally saw the signal() function, and I feel that there are many doubts about the prototype of this function. Let me learn it and share it by the way.

1. Prototype

The Unix system provides two functions, signal() and sigaction(), to change the processing method for signals. Among them, signal() is a glibc library function based on the sigaction() system call. Its behavior is different in different Unix operating systems. Programs that require portability cannot use the signal() function.

Its prototype is as follows:

#include<signal.h>
void ( *signal(int sig, void (*handler)(int)) )(int);

The first parameter sig of the signal function is to pass in the signal number of the processing function that you want to modify. The second parameter is a function pointer that does not return a value and accepts an int parameter, pointing to a new processing function for the sig signal. There are three options for the second parameter of the function. The first one is the signal processing function defined by ourselves. The second one is to pass in SIG_DFL to restore the signal processing method changed by the previous signal. The third one is to pass in SIG_IGN, which means the signal is ignored. The kernel will directly discard the signal and not pass it to the process.

The return value of the signal function is also a function pointer that does not return a value and accepts an int parameter. When the signal() function is successfully executed, the return value is a pointer to the processing function of the sig signal before the signal function is executed, and if it fails, SIG_ERR is returned.

It may be easier to understand by defining the signal processing function pointer like this:

//Define sighandler_t as a pointer to a function that returns void and accepts an int parameter 
typedef void (*sighandler_t)(int); 
//Now we can write the signal function 
sighandler_t signal(int sig, sighandler_t handler);

In fact, glibc already has the above definition. We only need to define the _GUN_SOURCE feature test macro to use the sighandler_t type.

2. Examples

The following usage is used to temporarily modify the signal handler of a signal, and reset the signal handler to its original version after use.

void newhandler(int sig){ 
    //code to handle the sig 
} 
void (*prevhandler)(int); //store the signal processing function before modification 
prehandler = signal(SIGINT, newhandler); 
if(prehandler == SIG_ERR)   
    cerr<<"Error in signal"<<endl; 
handler function*/ 
if(signal(SIGINT, prevhandler) == SIG_ERR) 
    cerr<<"Error in signal"<<endl;

Guess you like

Origin blog.csdn.net/JttiSEO/article/details/131662166