Linux Kernel notes-Signal

Source: Internet
Author: User
Linux Kernel notes-signals-Linux general technology-Linux programming and kernel information. The following is a detailed description. 1 Preface
The purpose of writing this article is slightly different from that of other articles, not for the system and comprehensive introduction of the "signal" subsystem, although it is not complex, the content is not covered by a short article, but to answer your own questions, solve some problems encountered in your work, and understand what cannot be understood immediately. In the end, we can regard this article as the answer to the question.
In the last question and answer section, you can scan the question before reading the text, which may help you better understand the content in the article.
You are welcome to comment on this article and correct, my email is:

2. License Agreement
The License agreement in this article complies with the GNU Free Document License. For more information, see You can freely disseminate or publish this article based on the GNU Free Document License, but keep the integrity of this article.

3. What is a signal?
Signals are a standard method for communication between UNIX processes. They already exist in the earliest UNIX systems. The appearance of the signal allows the kernel and other processes to notify the occurrence of a specific process event. There are other inter-process communication methods in modern UNIX, but they are still widely used due to the relatively simple and effective signal.
A signal is the simplest message. When a signal is sent, it has no parameters or other additional information. Only one integer represents the signal value. The value of a signal has been standardized in all UNIX systems. Each signal has a name that starts with a letter SIG and corresponds to a specific event. For example, SIGKILL indicates that the process is terminated; SIGBUS indicates that the hardware fails; SIGCHLD indicates that the sub-process status changes.
There are 31 commonly used signals in UNIX. In addition to the three signals mentioned above, the following signals are used in this article, and others are not listed one by one.
SIGSTOP pause Program Execution
SIGCONT Recovery Program Execution
3.1 process Signal Processing
A process can set a separate processing method for each signal. It can ignore the signal, set its own signal processing program (called capture), or do nothing about the signal, execute the default system action when the signal occurs.
The process can also set blocks for certain signals. If a signal is set to be blocked, it will be delivered to the process like a normal signal when the signal occurs, however, the process will be processed only when the process is blocked.
The interval between a non-blocking signal being delivered to a process and the signal being processed is called pending ). Some documents translate pending into "pending signals ".
In all signals, SIGSTOP and SIGKILL are special. They cannot be captured, ignored, or blocked, this feature ensures that the system administrator can use signals to pause and end the program at any time.
3.2 signal-related components in the Process Data Structure
Starting from this part, we will analyze the Linux kernel. In the kernel, a basic data structure sigset_t is used to represent signals. The length of sigset_t varies slightly in different CPU architectures. For Intel i386 architectures, sigset_t is a 64-bit integer, each representing a signal. The last 32 bits in Sigset_t represent real-time signals. The only difference between Sigset_t and common signals is that it supports queuing of the same signal, which ensures that multiple real-time signals are received. Real-time signals are part of the POSIX standard, but linux does not process them separately. Apart from queuing, they are not the focus of our attention.
The process structure task_struct contains the following data members and signal-related
L sigpending
A sign of the int type. If it is not 0, there is a pending non-blocking signal waiting for processing in the process.
L pending
Variable of the type struct sigpending. It can be seen as a process's signal queue, which stores all pending signals. For some signals, it also includes related information. For example, the SIGCHLD signal is sent to the parent process when the child process ends. Its Additional information includes the child process ID and end value.
L blocked
Variable of Type sigset_t. Indicates which signals are blocked in the current process.
L sig
Variable of the type struct signal_struct. Describes how a process processes each signal.
3.3 related functions
The following are system calls that are frequently used by processes to process signals.
L sigaction
Sets or reads how a process processes a signal. Processes can ignore or process the signal by default, or set their own signal processing programs.
L Sigprocmask
Sets or reads the signal blocking mask of a process.
L Sigpending
Returns the currently pending signal set. Blocked pending signals are not returned.
4. Signal Transmission
A signal is an asynchronous event. When a signal is sent to a process, the receiving process may run at any time and be in any State. To enable the program to process signals correctly when they are in different States, the system needs to pre-process the signals properly. The process we discuss actually includes signal generation and signal delivery. The detailed analysis is as follows.
4.1 Process status
From the status of the process itself, it may be in the RUNNING state (RUNNING), the waiting state (INTERRUPTBLE & UNINTERRUPTBLE), The STOPPED state (STOPPED) and the dead state (ZOMBIE ). In terms of the mode in which the process runs, it may be in either kernel mode or user mode,
4.2 Program Analysis
There are several methods to send signals to a process, but they will eventually call the send_sig_info function in the kernel to complete sending. In this function, the Kernel performs a series of checks. Only signals meeting the appropriate condition * are placed in the signal queue of the process. Then, it checks whether the program is in the INTERRUPTABLE state, if yes, it will wake up the process, change the state of the process to the RUNNING state, and put it in the system RUNNING queue.
The system has two interesting points in processing the sent signal:
1) only the SIGKILL and SIGCONT signals can be received by the STOPPED process.
All other signals are ignored. This is determined by the characteristics of the STOPPED state. It is set to control the execution and suspension of processes, and the SIGCONT signal can resume the execution of the suspended program, when SIGKILL is received, it can kill and suspend the process.
2) The signal that satisfies the appropriate signal is a series of inspection conditions:
. A) The sender process meets the requirements of the sender in POSIX.1.
. B) The process does not explicitly/implicitly ignore the signal.
. C) the process does not block the signal.
. D) The same signal has not been suspended in the process. The same signal of the same process is not queued. If a signal is sent multiple times consecutively and has been suspended in the receiving process, subsequent signals are discarded.
4.3 related functions
4.3.1 Kernel
L send_sig_info (kernel/signal. c)
The entry function used to send signals. All other functions use this function to send signals.
L force_sig_info (kernel/signal. c)
The forced signal sending function that is only used by kernel functions. It makes some efforts to ensure that the process can neither ignore nor block the signal, and then calls send_sig_info to send the signal.
4.3.2 user
L kill system call
The process sends signals to other processes through the kill system call. For the implementation of the kill system call in the kernel, see the sys_kill () function in kernel/signal. c. It calls send_sig_info to send signals.
Kill can send signals to a process or the entire process group. When the kill system is called, a negative receiving process ID ("pid") is specified, and the signal is sent to a process group whose ID is "-pid; if the recipient process ID is specified as-1, the signal is sent to all processes except itself, which is obviously a function that should not be used frequently.
5. Signal Processing
5.1 Signal Processing Program
The signal processing program is part of the execution program of the process. It can be executed only when the process is running on the CPU. That is to say, if the process cannot be executed, for example, the State is UNINTERRUPTABLE, STOPPED (as mentioned earlier, it can receive SIGKILL, SIGCONT signals) and other States. signals sent to processes will never be processed.
5.2 When to execute
The kernel will be called at specific time points. Specifically, after each system call ends, when the program returns from the kernel state to the user State and from the interrupt and Exception Code, [see arch/kernel/entry. the ret_from_sys_call code in the S file -- checks whether the current process has not processed any signal, and then calls the main function do_signal of signal processing.
5.3 Program Analysis
As a main function, do_signal has a lot to note. It cyclically works, and each loop extracts an outstanding signal from the process. The order of the signal is from small to large and then processed. The process is as follows:
1) if the program is being tracked, the program will be transferred to the STOPPED state, and a SIGCHLD signal will be sent to the tracker. One interesting thing is: how does a program run after it gets the right to run again?
2) If the signal processing operation ignores the signal, the cycle is completed immediately, but the SIGCHLD signal is an exception. It calls the sys_wait4 function to force the process to read the information of the sub-process, to clear the memory left by the terminated sub-process.
3) if the signal processing operation is the default processing, do_signal will execute the default signal operation. An exception is that when the receiving process is init, the signal is discarded and the loop is completed immediately.
Default operations for different signals are different and can be divided into four categories. The default operations for the first type of signals are ignored, such as SIGCHLD signals. The second type of signals will transfer the process to the stop State (note, it is not the end process), for example, the SIGSTOP signal; the third type of signal will end the process and write the status before the end to the core file, for example, the SIGSEGV signal indicating illegal memory access; other Signals simply end the process (do_exit function), such as the SIGKILL signal.
4) Finally, call the signal processing program of the process to process the signal. After the call is completed, do_signal returns directly, that is, unlike other signals processed through loops, only one signal with its own signal processing function can be processed in one do_signal call. The reason for this is that, unlike other signal processing methods, the signal processing function of a process is a user State function, which cannot be called directly in the do_signal loop; otherwise, it will bring serious security problems, what do_signal can do is to set the execution register environment and stack code of the program, so that the process returns to the user State and first executes the signal processing function. Setting the stack environment of a process is a complicated task. It is worth using another article to explain it separately. I will not repeat it here. refer to the specific code arch/kernel/signal. handle_signal function in c.

5.4 related functions
All related functions are in the kernel state.
L ret_from_syscall
After the system call ends, the function executed before the user State is returned. It checks whether there are pending signals in the process and calls the do_signal function to process the pending signals. Ret_from_syscall is located in the arch/kernel/entry. S Assembly file. It is not a function, but an assembly language program. The caller uses the jmp command to access it.
L do_signal
Main function of signal processing. Located in the arch/kernel/signal. c file.
L handle_signal
Processes signals with "Custom signal processing functions" and completes complex tasks such as stack creation.
6. signal and system call
6.1 Allow System Calls interrupted by signals
Normally executed system calls are not interrupted by signals, but some system calls may take a long wait to complete. In this case, allowing the signal to interrupt its execution provides better program control capabilities. To enable the function to be interrupted by signals, the following conditions must be met:
The system call must switch the process to sleep state when waiting to take the initiative to let out the CPU. As a kernel-State Program, the execution of system calls cannot be preemptible. system calls that do not voluntarily give up the CPU will continue to run until the end. In addition, the sleep status of the current process must be set to TASK_INTERRUPTABLE. Only in this status, when the signal is sent to the process, the process status is awakened by the signal sending function, and wait for scheduling again in the running queue.
When a process obtains a CPU time slice, it then runs the next command during sleep (still in the system call), and the system call determines that the signal is received, A exit sign related to the signal is set and the exit sign ends quickly. Exit flag is one of ERESTARTNOHAND, ERESTARTSYS, and ERESTARTNOINTR. These flags are used to communicate with the receiving signal program do_signal. They are used together with the process's processing marks for specific signals, determines whether to re-execute the call after the system call is interrupted.
ERESTARTNOINTR: requires that the system call be re-executed unconditionally.
ERESTARTSYS: The system call is required to be re-executed, but the signal processing program is allowed to choose based on its own flag.
ERESTARTNOHAND: when the signal does not set its own signal processing function, the system calls and re-executes the function.

6.2 re-execution of system calls
At the end of the system call, the do_signal function is executed. It will decide whether to re-execute the system call together with the exit sign of the system call. The do_sigal function needs to process two cases. One is that the process sets its own signal processing program for the received signal, the other is that the process does not set the signal processing program for the received signal, and after processing all the signals, the process is not stopped or ended. In the latter case, do_signal restarts the system call when the exit flag of the system call is ERESTARTNOHAND, ERESTARTSYS, or ERESTARTNOINTR. In the previous case, the system call can be restarted only when the exit sign of the system call is ERESTARTNOINTR or ERESTARTSYS and the signal processing sign meets the conditions.
6.3 related functions
L sys_sigaction
The system calls the implementation of sigaction. Through the sigaction system call, the process can set the processing program and processing flag for specific signals. One of the Flag SA_RESTART affects whether the system call can be re-executed.
7. Questions and answers
L Why can a process be interrupted by a signal when it is blocked by a system call, but cannot be interrupted when it is blocked by another system call?
As described in the "signals and system calls" section, only system calls that block processes in the TASK_INTERRUPTABLE mode can be interrupted. System calls that are blocked in the TASK_UNINTERRUPTABLE mode cannot be interrupted.
L how does the system ensure that the SIGKILL/SIGSTOP signals cannot be captured or ignored?
The process sets the signal processing method by calling sigaction. the implementation function of sigaction in the kernel is sys_sigaction (kernel/signal. c) It checks the signal value transmitted by the process to ensure that the signal SIGKILL and SIGSTOP cannot be set.
The other two systems call sigprocmask and sigsuspend to change the signal shielding characters. Similar to sigaction, their implementation functions in the kernel will check the parameters to ensure that SIGKILL and SIGSTOP are not blocked.
L what are the differences between blocking and ignoring signals?
The blocking signal allows the signal to be sent to the process, but does not process it. You need to wait until the blocking is removed before processing. Ignoring the signal means that the process does not receive the signal at all, and all ignored signals are discarded.
The system calls sigprocmask and sigsuspend to set whether the signal is blocked or not, while the system calls sigaction to set whether the process ignores a signal.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.