Signal mechanism in Linux kernel-a simple example
Author:Ce123. (http://blog.csdn.net/ce123)
Signal mechanism is an important means of inter-process communication in Unix-like systems. We often use signals to send a short message to a process. For example, if we start a process to read network data packets sent from the remote host through socket, the host has not received the corresponding data due to network factors, the current process is set to the interrupted wait state (task_interruptible). At this time, we have lost patience and want to end the process ahead of schedule. Therefore, we can run the kill command to send a kill signal to the process, the kernel will wake up the process and execute its signal processing function. The default kill signal processing is to exit the process. Of course, it is not necessary for a process to be In the task_interruptible state to process signals.
In addition, applications can use functions such as signal () to set the default processing function for a signal. For example, when you press Ctrl + C, shell will send a SIGINT signal. The default processing function of SIGINT is the exit code of the execution process, however, the following example sets the response function of SIGINT to int_handler.
#include <signal.h>#include <stdio.h>void int_handler(int signum){printf("\nSIGINT signal handler.\n");printf("exit.\n");exit(-1);}int main(){signal(SIGINT, int_handler);printf("int_handler set for SIGINT\n");while(1){printf("go to sleep.\n");sleep(60);}return 0;}
When executing the code above, first execute the main function, set the processing function of SIGINT, and enter the sleep state. The process enters the pendable waiting state:
After pressing CTRL + C, the process will be awakened to execute the int_handler () function of SIGINT, and the process will exit.
· Signal distribution and processing are carried out in the kernel state. When you can read a book from the preceding example, the signal processing function may be in the user State. In this case, the kernel needs to build a temporary user-state environment and then call the user-state signal processing function.