Linux basic series-signal and signal processing

Source: Internet
Author: User
Tags sigint signal

The basic series is better than the subsystem series. Most of these series are excerpted. Many brothers have made a good conclusion before and thank you for choosing them.

I have recently dealt with a debugging problem involving Linux signals. I would like to summarize it here for a memo.

++ ++

Directory:

1. Linux Signal

2. Signal Processing

3. How to process signals in debug

4. How to Write secure signal processing functions in multi-threaded applications

 

I. Linux Signal

1. Concept

 

A signal is a simulation of the interrupt mechanism at the software level. In principle, a process receives a signal and the processor receives an interrupt request. The signal is asynchronous. A process does not have to wait for the signal to arrive through any operation. In fact, the process does not know when the signal will arrive.

Signals are the only asynchronous communication mechanism in the inter-process communication mechanism. They can be seen as asynchronous notifications to notify the processes that receive signals of what happened. After POSIX real-time expansion, the signal mechanism is more powerful. In addition to the basic notification function, it can also transmit additional information.

 

 

There are two sources for the occurrence of signal events: hardware sources (for example, we press the keyboard or other hardware faults); software sources, the most common system function for sending signals is kill, raise,
Alarm, setimer, and sigqueue functions. The software source also includes some illegal operations.

2. Category

 

In earlier Unix systems, only 32 types of signals are defined. In Linux, 64 types of signals are supported, numbered 0-63 (sigrtmin = 31, sigrtmax = 63), which may be further increased in the future, this requires Kernel support. The first 32 signals have predefined values. Each signal has a definite purpose and meaning, and each signal has its own default action. For example, press Ctrl on the keyboard.
^ C, a sigint signal is generated. The default response to this signal is that the process is terminated. The last 32 signals represent real-time signals, that is, reliable signals. This ensures that multiple real-time signals are received. Real-time signals are part of the POSIX standard and can be used in application processes.

 

Non-real-time signals do not support queuing and are all unreliable signals. Real-time signals support queuing and are all reliable signals.

 

 

The signal value between sigrtmin and sigrtmax is a reliable signal, which overcomes the possibility of signal loss. Linux supports the new version of the signal installation function sigation () and the signal sending function sigqueue (). It also supports the early signal () signal installation function and the signal sending function kill ().

Note that the signal sent by sigqueue () and installed by sigaction is reliable. In fact, a reliable signal is a new signal added later (the signal value is located between sigrtmin and sigrtmax). An Unreliable signal is a signal whose signal value is smaller than sigrtmin. The signal reliability is only related to the signal value, and is not related to the signal sending and installation functions. Currently, signal () in Linux is implemented through the sigation () function. Therefore, even if the signal installed by signal () is, at the end of the signal processing function, you do not have to call the signal installation function again. At the same time, real-time signals installed by signal () Support queuing and will not be lost.

 

 

2. Signal Processing

 

If a process needs to process a signal, it must be installed in the process. The installation signal is mainly used to determine the ing between the signal value and the action of the process against the signal value, that is, the signal to be processed by the process, and the operation to be performed when the signal is transmitted to the process.

Linux mainly has two function implementation signals: Signal () and sigaction (). Signal () is implemented based on reliable signal system calls,
Is a library function. It has only two parameters and does not support signal transmission information. It is mainly used for the installation of the first 32 non-real-time signals, while sigaction () is a newer function (called by two systems: sys_signal and sys_rt_sigaction), which have three parameters, support signal transmission information, mainly used
Sigqueue ()
System calls are used together. Of course, sigaction () also supports installation of non-real-time signals. Sigaction () is superior to signal () mainly because it supports signal parameters.

 

 

3. How to process signals in debug

GDB can usually capture the majority of the signals of the tasks sent to him. By capturing the signals, it can decide what to do for running processes.

When a task is traced, Every time GDB receives a signal, the task is stopped, and GDB determines how to process the signal (according to the signal content, handle command settings, etc ), continue to execute the task according to the result. This is the behavior of ptrace, which can be seen from freindly man ptrace.

 

4. How to Write secure signal processing functions in multi-threaded applications

1. Background

When developing multi-threaded applications, developers generally consider thread security and usepthread_mutex
To protect global variables. If a signal is used in the application, and the signal is generated not because the program is running incorrectly, but because the program logic is required, such as SIGUSR1, sigrtmin
After the signal is processed, the application will still run normally. When writing such signal processing functions, developers at the application layer often ignore the context background of the signal processing function execution and do not consider writing secure signal processing functions. Here we will introduce some rules to consider when writing a signal processing function:

Because the signal is an asynchronous event, that is, the context of the execution of the signal processing function is uncertain. For example, a thread may be interrupted by the signal when calling a library function, and the library function returns an error in advance, instead, execute the signal processing function. For the generation of the third signal, after the signal is generated and processed, the application will not terminate or continue to run normally. You must be especially careful when writing such signal processing functions, to avoid disrupting the normal operation of applications. There are several rules for writing secure signal processing functions:

  • As far as possible, the signal processing function only performs simple operations, such as setting an external variable, and other complex operations are executed outside the signal processing function;
  • errnoIs thread security, that is, each thread has its own
    errno
    But not asynchronous signal security. If the signal processing function is complex and the call may change errno
    Value library function, you must consider restoring the interrupted thread when the signal processing function is saved and ended. errnoValue;
  • The signal processing function can only call the C-database function that can be reinjected. For example, the function cannot be called. malloc(),free()And standard I/O library functions;
  • If the signal processing function needs to access the global variable, it must be declaredvolatile,To avoid improper Compiler optimization.

From the perspective of the Linux application, because asynchronous signals are used in the application, some library functions in the program may be interrupted by asynchronous signals during calling.errno
Consider the error recovery processing after these library function calls are interrupted by the signal.

 

Obviously, writing an asynchronous signal processing function is like a thin ice. If you don't pay attention to it, you will forget a certain principle and become a hidden danger (writing a secure asynchronous signal processing function is bound by many rules; when calling database functions that can be interrupted by signals elsewhere in the application, you must consider error recovery after interruption ).

 

2. Solution

Fortunately, the posix.1 Specification definessigwait()、 sigwaitinfo() And
pthread_sigmask()To:

  • Asynchronous Signal Processing in synchronous mode;
  • Processes signals in a specified thread.

This model of synchronous signal processing in the specified thread can avoid the uncertainty and potential danger caused to the program running by processing asynchronous signals.

Sigwait

sigwait()
It provides a mechanism to extract signals from the signal queue in serial mode for processing when the signal arrives.sigwait(Only wait for the signal set specified in the function parameter. That is, if the new signal is not in the specified signal set
sigwait()
Wait.

 

sigwaitinfo() And sigtimedwait() It also provides
sigwait()
Functions are similar.

 

Therefore, we can build our model as follows:

  1. The main thread sets a signal mask, which hinders the signal to be processed synchronously. The signal mask of the main thread is inherited by the thread it creates;
  2. The main thread creates a signal processing thread. The signal processing thread sets the signal set sigwait().
  3. The main thread creates a working thread.

3. Summary

In Linux-based multi-threaded applications, you can consider using a Synchronization Model to process signals generated due to program logic needs. signals that cause program running termination, such as SIGSEGV
And must be used in the traditional asynchronous mode.signal(),
sigaction()Register the signal processing function for processing. The two signal processing models can exist in a Linux application at the same time according to different signals:

  • Do not block the sigstop and sigkill signals that cannot be ignored in the signal mask of the thread.
  • Do not block sigfpe, sigill, SIGSEGV, and sigbus in the signal mask of the thread.
  • Ensure sigwait() The waiting signal set has been blocked by all threads in the process.
  • Must be called when the main thread or other worker threads generate signals kill() Send the signal to the entire process, instead of using
    pthread_kill()
    Send a specific worker thread. Otherwise, the signal processing thread cannot receive the signal.
  • Because
    sigwait()The serial method is used to process the arrival of signals. To avoid lag in signal processing or the loss of non-real-time signals, the code for processing each signal should be as concise and fast as possible, avoid blocking library functions.

 

Note:

  • For non-real-time signals, the same signal cannot be queued in the signal queue; for real-time signals, the same signal can be queued in the signal queue.
  • If there are multiple real-time and non-real-time signal queues in the signal queue, the real-time signal will not be taken out before the non-real-time signal. If the signal number is small, it will be taken out first: for example, SIGUSR1 (10) will be prior to sigusr2
    (12), sigrtmin (34) is prior to sigrtmax (64). Non-real-time signals are extracted prior to real-time signals because their signal numbers are small.

 

 

 

 

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: info-contact@alibabacloud.com 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.