Linux signal signal processing system

sponsored links
Original Address: http://blog.chinaunix.net/u2/63021/showart_1678393.html

Linux programming signal is a very important part, this article details the basic concepts of signaling mechanism, Linux signal mechanism for the general implementation method, how to use signals, Yijiyouguan call signal of several systems.

Signaling mechanism is the process of passing messages between a method known as soft interrupts the whole signal, it was also known as soft interrupts. Can be seen from its name, its essence and use it like a break. Therefore, the signal can be said to be a part of process control.

First, the basic concepts of signal

This section first introduces some basic concepts of signal, and then give some basic signal types and signal the corresponding event. Basic concepts for understanding and use of signals, for understanding the signaling mechanisms are particularly important. Take a look what is the signal.

1, the basic concept

Soft interrupt signal (signal, also known as the signal) is used to inform the process of asynchronous event occurred. Process between the system call kill each other by sending soft interrupt signal. Kernel can also be due to internal events and send a signal to the process, notification process an event occurred. Note that the signal is only used to notice what happened to a process, not to pass any data in the process.

The process received signals to various signals have different approaches. Treatment can be divided into three categories: The first is similar to the interrupt handler, the signal for the need to address, the process can specify the handling functions from the function to deal with. The second approach is to ignore a signal, the signal without any processing, just as the same has not happened. The third approach is to keep the signal processing system, the default value, this default action, most of the signal on the default action is to make the process terminates. Process through the system call signal to the specified process on a signal processing behavior.

In the process table entry has a soft interrupt signal domain, the domain each corresponding to a signal, when a signal is sent to the process, the corresponding bit. It can be seen, the process can be different while retaining the signal, but for the same signal, the process does not know how many came before processing.

2, the type of signal

Signal for many reasons, the reasons for a signal here by a simple classification, in order to understand a variety of signals:

(1) associated with the process to terminate the signal. When the process exit, or the child process terminates, the issue of such signals.
(2) and the processes related to signal exceptional events. If the process of cross-border, or an attempt to write a read-only memory area (such as program text area), or execute a privileged instruction, and other types of hardware error.
(3) and the system call encountered an unrecoverable condition during the relevant signal. Such as the implementation of the system call exec, the existing resources have been released, and the present system resource has been depleted.
(4) and the implementation of the system call encountered conditions of non-prediction error signal. Such as the implementation of a system call that does not exist.
(5) in the user mode processes under the given signal. If the process is called system calls kill to send signals to other processes.
(6) interact with the terminal-related signals. If the user closes a terminal, or press the break key and so on.
(7) to track the process of implementation of the signal.

Linux support for the signal list is as follows. Many signals are associated with the machine architecture, the first listed is listed in POSIX.1 signal:

Signal value of the reasons for signal processing actions
-------------------------------------------------- --------------------
SIGHUP 1 A terminal suspend or terminate the control process
SIGINT 2 A keyboard interrupt (such as the break key is pressed)
SIGQUIT 3 C keyboard eject button is pressed
SIGILL 4 C Illegal Instruction
SIGABRT 6 C by the abort (3) withdrawal orders issued
SIGFPE 8 C Floating point exception
SIGKILL 9 AEF Kill signal
SIGSEGV 11 C Invalid memory reference
SIGPIPE 13 A pipeline rupture: there is no time to write a port of the pipeline
SIGALRM 14 A from the alarm (2) signals
SIGTERM 15 A Termination signal
SIGUSR1 30,10,16 A User-defined signal 1
SIGUSR2 31,12,17 A User-defined signal 2
SIGCHLD 20,17,18 B signal the end of child process
SIGCONT 19,18,25 process continues (the process had been stopped)
SIGSTOP 17,19,23 DEF terminate the process
SIGTSTP 18,20,24 D control terminal (tty) press the stop button
SIGTTIN 21,21,26 D background process attempting to read from the control terminal
SIGTTOU 22,22,27 D Terminal background process tries to write

The following signals not listed in POSIX.1, but listed in SUSv2

Signal value of the reasons for signal processing actions
-------------------------------------------------- ------------------
SIGBUS 10,7,10 C bus error (bad memory access)
SIGPOLL A Sys V defined Pollable event, synonymous with SIGIO
SIGPROF 27,27,29 A Profiling timer to
SIGSYS 12, -, 12 C invalid system call (SVID)
SIGTRAP 5 C trace / breakpoint capture
SIGURG 16,23,21 B Socket emergency conditions (4.2 BSD)
SIGVTALRM 26,26,28 A real time alarm clock (4.2 BSD)
SIGXCPU 24,24,30 C CPU time limit beyond the set (4.2 BSD)
SIGXFSZ 25,25,31 C File size limit beyond the set (4.2 BSD)

(For SIGSYS, SIGXCPU, SIGXFSZ, and under certain machine architecture SIGBUS, Linux default action is A (terminate), SUSv2 is C (terminate and dump core)).

Here are some other signals

Signal value of the reasons for signal processing actions
-------------------------------------------------- --------------------
SIGIOT 6 C IO capture command, synonymous with SIGABRT
SIGEMT 7, -, 7
SIGSTKFLT -, 16, - A coprocessor stack fault
SIGIO 23,29,22 A certain I / O operations can now be carried out (4.2 BSD)
SIGCLD -, -, 18 A synonymous with SIGCHLD
SIGPWR 29,30,19 A power failure (System V)
SIGINFO 29, -, - A synonym with SIGPWR
SIGLOST -,-,- A file lock is lost
SIGWINCH 28,28,20 B Window size change (4.3 BSD, Sun)
SIGUNUSED -, 31, - A Unused signal (will be SIGSYS)

(Here, - the signal did not materialize; there are three values give meaning to, the first value in the Alpha and Sparc are usually valid, the middle value corresponds to i386 and ppc and sh, the last value corresponds to mips. Signal 29 in the Alpha for the SIGINFO / SIGPWR, the Sparc for the SIGLOST.)

The letters deal with the meaning of an action as follows
A default action is to terminate the process
B The default action is to ignore the signal
C The default action is to terminate the process and make the kernel image dump (dump core)
D default action is to stop the process
E signal can not be captured
F signal can not be ignored

Signal described above is a common system support. Presented in tabular form the names of various signals, and its default processing action. Handle a variety of default is the meaning of action: terminate the process is the process of withdrawal; ignore the signals of the signal is discarded, not treated; stop the program is the program hangs, after the stop condition can go back to the general is debugging process (such as ptrace system call); core image dump refers to the process image data in memory and process structures in the kernel part of a certain format to the file system dump, and withdraw from the process of doing so advantage of the convenience for the programmers, so they can get the implementation process at that time when the data value, allowing them to determine the dump of the reasons, and can debug their programs.

Note that signals SIGKILL and SIGSTOP neither can be captured and can not be ignored. SIGIOT with SIGABRT signal is a signal. Can be seen, the same signal values in different systems may be different, it would be best to use defined names for the signal, but do not directly use the value of the signal.

Second, the signal mechanism

The previous section introduced the basic concept of the signal, in this section, we introduce the kernel how signaling mechanism. The kernel how to send a signal to a process, the process of how to receive a signal, the process of how to control my response to the signal, the kernel in what circumstances the process of treatment and how to deal with the signal received. Setjmp and longjmp also describe the role of the signal.

1, the basic core of the signal processing method

The kernel to send a soft interrupt a process approach, where the process is in the process table entry of the signal field settings corresponding to the signal bit. Here we add that, if the signal is sent to a process is sleeping, it depends on the process priority of sleep, sleep if the process can be interrupted in the priority on the wake-up process; otherwise, set the process in the table only the signal domain corresponding bit, and not wake up the process. This point is more important, because the process checks whether the received signal Shiji is: a process in Ji Qiang from the kernel state returned to the user Tai O'clock; Huozhe, in a process to enter or Li Kai a Shidang of low sleep Zhuang Tai Ji You Xian when scheduling.

Kernel processing a received signal timing of the process is a process in user mode from kernel mode back to the time. So, when a process running in kernel mode, the software interrupt does not work immediately until the return to user mode when processing. Process only the processed signal will return to user mode, the process in user mode will not be processed under the complete signal.

Kernel processing a process of soft interrupt signal is received in the context of the process, therefore, the process must be running. When the concept described above have said, there are three types of signal processing: the process exit signal is received; process ignore the signal; process, the implementation of user-defined signal is received signal with the system call function. When the process receives a signal when it is ignored, the process of discarding the signal, as did not receive the signal like to continue running. If the process receives a signal to be captured, then the process return to user mode from kernel mode to execute user-defined functions. And implementation of user-defined function method is very clever, the kernel is a user stack to create a new layer, the layer will return the address value set to user-defined function to the address, so that the process of return to pop up the stack from the kernel when to return to the user-defined function office, and then pop the stack to return from the function only when the return to the original place into the kernel. The reason is the user-defined processing functions can not and does not allow the kernel state are executed (if the user-defined functions running in kernel mode, the user can get any privileges).

In the signal processing method in a few particular attention. First, in some systems, when a process of processing the interrupt signal back to user mode before the kernel set clear user area of the signal processing routine address, that is, the next process in the signal processing method has changed the default value, unless the signal before the arrival of the next signal system call again. This may make the process before the call signal has been caused by the signal out. In BSD, the kernel is not clear that address. But does not clear the address may make the process as too much too fast to get a signal and cause a stack overflow. To avoid this situation. In the BSD system, the kernel of the hardware interrupt simulation approach, that is, when dealing with a break, stop receiving new kind of disruption.

The second to draw attention to yes, if the signal occurs to capture process is a system call, the Bing Qiegai process of Youxian interruptible sleep in class Shang, then process the signal Yin Qi Zuo Yi Ci longjmp, out of Shuimianzhuangtai, return to user mode and perform signal processing routines. When the return from the signal processing routine, the process as from the system call returns the same, but returned an error code, pointing out that the second system call was interrupted. It should be noted that, BSD system can automatically restart the kernel system calls.

The third place to note: if the process can sleep in the priority of the interrupt, then when it receives a signal to ignore, the process is awakened, but do not do longjmp, generally continue to sleep. However, users do not feel the process had been awakened, but as there has not been the same as the signal.

Fourth place to note: the kernel pair process terminates (SIGCLD) signal processing methods differ from other signals. When the process of checking out before a child process to terminate the signal, by default, as the process does not receive the signal like, if the parent process of the implementation of the system call wait, the process from the system call to wake up and wait Back wait call, the implementation of a series of follow-up action calling wait (to identify dead child process, the release of the child process process table entry), and then wait to return. SIGCLD a wake-up signal is the role of sleep can be interrupted in the process of priority. If the process caught the signal, the same as ordinary signal processing routines to deal with. If the process ignores the signal, then the system call wait for action to be different, because SIGCLD is simply to awaken a sleep can be interrupted in the process of priority, then the implementation of the wait wake up call to the parent process calls wait to continue follow-up operation, and then wait for the other child processes.

If a process called signal system call, and set the SIGCLD approach, and the state into the Cheng Youzi process is dead, then the kernel will send a SIGCLD signal of the process.

2, setjmp and longjmp role

Before introducing the signal processing mechanism, repeatedly referred to the setjmp and longjmp, but did not carefully explain their role and implementation methods. Here to give us a brief introduction.

In introducing the signal, we see several local claims process after checking the signal received from the original system call returns directly, rather than waiting until the completion of the call. This process of sudden change in the context of the situation, is to use setjmp and longjmp results. setjmp will save the context into the user area, and continue to perform in the old context. That is, the process of implementing a system call, when resources or other reasons, because when going to sleep, the kernel for the process made a setjmp, signal if the sleep is awakened, the process can not go to sleep, the kernel for the process of calling longjmp, The operation is the original kernel for the process to call up the saved setjmp user Ou De context in the process restored to the present context, the process of Ke Yi Zhe Yang to Shi De resume Dengdaiziyuan the status before and the core is setjmp Fan Hui 1, making the process know that Gai plays Xitongtiaoyong Shibai . This is their role.

Third, the signal system call

The previous two sections have introduced the most knowledge about the signal. In this section we come to understand how these system calls. Among them, the system call signal is the process used to set a signal processing method, system call kill is used to send signals to the specified process. These two calls can form the basic operation of the signal. After two calls pause and alarm signals to achieve through the process of suspension and the timer, call the alarm signal to inform the process through the timer to time. So here we have introduced the two calls.

1, signal system call

System call signal used to set a signal processing method. The format of the call statement is as follows:
void (* signal (int signum, void (* handler) (int))) (int);
In the course of using the call by adding the following header file:
# Include <signal.h>

These statements form more complex, if not sure how to use this type can also be defined in the following format to use (POSIX defined):
typedef void (* sighandler_t) (int);
sighandler_t signal (int signum, sighandler_t handler);
But this format in different systems have different types of definitions, so use this format, best refer to the online manual.

In the call, the parameter signum that the signal processing method to be set. The second parameter handler is a function, or
SIG_IGN: ignore the parameters within the meaning of the signal signum.
SIG_DFL: recovery parameter signum signal processing method referred to as the default value.

Passed to the signal processing routines of the integer parameter is the signal value, so you can make a signal processing routine to handle multiple signals. System call signal the return value is the specified signal signum previous error handling routine, or return an error code SIG_ERR. The following look at a simple example:

# Include <signal.h>
# Include <unistd.h>
# Include <stdio.h>
void sigroutine (int dunno) (/ * Signal processing routines, which will be the signal dunno values * /
switch (dunno) (
case 1:
printf ("Get a signal - SIGHUP");
break;
case 2:
printf ("Get a signal - SIGINT");
break;
case 3:
printf ("Get a signal - SIGQUIT");
break;
)
return;
)

int main () (
printf ("process id is% d", getpid ());
signal (SIGHUP, sigroutine); / / * The following set of three signal processing methods
signal (SIGINT, sigroutine);
signal (SIGQUIT, sigroutine);
for (;;);
)

One signal SIGINT issued by the Press Ctrl-C, the signal SIGQUIT by pressing Ctrl-issue. The results of the implementation of the program are as follows:

localhost: ~ $. / sig_test
process id is 463
Get a signal-SIGINT / / press Ctrl-C the results obtained
Get a signal-SIGQUIT / / press Ctrl-obtained results
/ / Process by pressing Ctrl-z will be placed in the background
[1] + Stopped. / Sig_test
localhost: ~ $ bg
[1] +. / Sig_test &
localhost: ~ $ kill-HUP 463 / / send a SIGHUP signal to the process
localhost: ~ $ Get a signal - SIGHUP
kill -9 463 / / send the SIGKILL signal to the process, termination process
localhost: ~ $

2, kill system call

System call kill to send a signal to the process. The format of the call statement is as follows:
int kill (pid_t pid, int sig);
In the process of using the call by adding the following header file:
# Include <sys/types.h>
# Include <signal.h>

The system call can be used in any process or process group to send any signal. If the argument pid is positive, then the call to send a signal sig to process pid process number. If pid equals 0, then signal sig is sent to the current process belongs to all processes in process group. Pid equal to -1 if the parameter, the signal sig is sent to process 1 and in addition to all processes other than their own. If the parameter pid is less than - 1, the signal sig is sent to process group-pid of all processes. Sig is 0 if the argument will not send the signal. The call is executed, the return value is 0; error, return -1 and set the appropriate error code errno. Here are some possible error codes returned:
EINVAL: invalid specified signal sig.
ESRCH: parameters of the process pid or process group specified does not exist. Note that in the process table entry exists in the process, may be a wait has not been recovered, but had been suspended and rigid process.
EPERM: the process has no power to the signal sent to the process designated to receive the signal. Because a process is allowed to send a signal to the process pid, the must have root authority, or the calling process with the UID or EUID of the process designated to receive the UID or the saved user ID (savedset-user-ID) the same. If the parameter pid is less than -1, that is, the signal is sent to a group, then the error that there are members of the group process can not receive the signal.

3, pause system call

The role of system calls pause to wait for a signal. The statement calls the following format:
int pause (void);
In the process of using the call by adding the following header file:
# Include <unistd.h>

The call allows the calling process to sleep until it receives a signal so far. The calls always return -1 and set the error code EINTR (receiving a signal). Here is a simple example:

# Include <unistd.h>
# Include <stdio.h>
# Include <signal.h>
void sigroutine (int unused) (
printf ("Catch a signal SIGINT");
)

int main () (
signal (SIGINT, sigroutine);
pause ();
printf ("receive a signal");
)

In this case, the program started, as into the infinite loop, this is because the process is waiting for the signal, when we press Ctrl-C, the signals were captured, and to make pause Tuichu wait state.

4, alarm and setitimer system calls

Alarm system calls the function is to set a timer when the timer time arrives, will send a signal to the process. The statement calls the following format:
unsigned int alarm (unsigned int seconds);
In the process of using the call by adding the following header file:
# Include <unistd.h>

Alarm arrangement kernel system call for the calling process specified seconds seconds to send a SIGALRM signal. If the specified parameter seconds is 0, then no longer send the SIGALRM signal. One set will be canceled after the previous settings. Last time the call returns a value between calls to send the remaining time, or because there is no time before the first call and return 0.

Note that, in use, alarm is only set to send a signal, to many to send, we must repeatedly use the alarm call.

For the alarm, there is no longer an example. The current system, many procedures no longer use alarm calls, but calls to set the timer to use setitimer with getitimer to get the status of the timer, the two statements call the following format:
int getitimer (int which, struct itimerval * value);
int setitimer (int which, const struct itimerval * value, struct itimerval * ovalue);
In the process of using these two calls to add the following header file:
# Include <sys/time.h>

The system call to process the three timers, their respective domain has its own unique time, when one no one arrived, the signal on the transmission of a corresponding to the process, and Shi De timer re-start. 3 timer specified by the parameters of which, as follows:
TIMER_REAL: real time by time, time to reach the process will send a SIGALRM signal.
ITIMER_VIRTUAL: only when only when the process execution time. Arrival time to process the signal will be sent SIGVTALRM.
ITIMER_PROF: When the process of implementation and systems for the process of implementation of the action when all time. And ITIMER_VIR-TUAL is a right, the timer is often used statistical process in user mode and kernel mode time spent. Arrival time will be sent SIGPROF signal to the process.

Timer timer parameter value is used to specify the time, its structure is as follows:
struct itimerval (
struct timeval it_interval; / * next value * /
struct timeval it_value; / * The set value * /
);

The structure timeval structure is defined as follows:
struct timeval (
long tv_sec; / * seconds * /
long tv_usec; / * microseconds 1 second = 1000000 microseconds * /
);

In setitimer call, parameter ovalue if not empty, then the retention of which is the last call to set the value. Timer will it_value reduced to 0, generate a signal, and the value is set to it_interval it_value value, and then re-start time, so back and forth. When it_value set 0, the timer stops, or when it expires time, the it_interval to 0 to stop. Call successful, return 0; error, return -1 and set the appropriate error code errno:
EFAULT: parameter value or ovalue is invalid pointer.
EINVAL: parameters which are not ITIMER_REAL, ITIMER_VIRT or ITIMER_PROF one.

Here is a simple demonstration setitimer call, in which case, every second to send a SIGALRM, SIGVTALRM every 0.5 seconds to send a signal:

# Include <signal.h>
# Include <unistd.h>
# Include <stdio.h>
# Include <sys/time.h>
int sec;

void sigroutine (int signo) (
switch (signo) (
case SIGALRM:
printf ("Catch a signal - SIGALRM");
break;
case SIGVTALRM:
printf ("Catch a signal - SIGVTALRM");
break;
)
return;
)

int main () (
struct itimerval value, ovalue, value2;
sec = 5;

printf ("process id is% d", getpid ());
signal (SIGALRM, sigroutine);
signal (SIGVTALRM, sigroutine);

value.it_value.tv_sec = 1;
value.it_value.tv_usec = 0;
value.it_interval.tv_sec = 1;
value.it_interval.tv_usec = 0;
setitimer (ITIMER_REAL, & value, & ovalue);

value2.it_value.tv_sec = 0;
value2.it_value.tv_usec = 500000;
value2.it_interval.tv_sec = 0;
value2.it_interval.tv_usec = 500000;
setitimer (ITIMER_VIRTUAL, & value2, & ovalue);

for (;;);
)

Copy the example of the screen as follows:

localhost: ~ $. / timer_test
process id is 579
Catch a signal - SIGVTALRM
Catch a signal - SIGALRM
Catch a signal - SIGVTALRM
Catch a signal - SIGVTALRM
Catch a signal - SIGALRM
Catch a signal-GVTALRM
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Linux signal signal processing system

  • Interact with Ruby and serial

    Recent study at the serial number of things about Ruby on trial today, the serial operation of the modem to send and receive return instructions. More powerful the code in the windows are also able to work rubynroll wrote File IO only by the lack of ...

  • At top monitor window displays the status of ongoing Rails request URL

    http://robbin.javaeye.com/blog/283992 This is from a PragDave's blog Above to learn skills, very useful, very cool! Saying in a Rails site running the above, we can use Linux's top command to monitor the Rails application instances running co ...

  • What we all namespaces (namespace) deal with mechanisms to deal with the javascript?

    Project needs, the requirements of the JS's namespace management, so the Internet looking for relevant information at the relevant forums mootools find a: Now what kind of U.S. approach to the JS namespace realize the problem? Can share released ...

  • Rails at RAS4 install some of the problems encountered

    RAS4 is already old, and if possible we should not use the recommended things, above What is missing , had to install a lot of things go their own or with RAS5, either with the server version of Ubuntu you! 1, require 'irb / completion' prompt

  • Robbin on the PHP / Ruby some concluding

    Robbin forward to the PHP forum on some conclusion, it is not picky:) collection of Quote PHP and Python / Ruby operating mechanism has an essential difference between: PHP are each HTTP request coming after the initialization of all resources (such ...

  • Ruby Server

    sudo vi / etc / apt / sources.list deb http://mirror.pacific.net.au/linux/ubuntu/ gutsy universe restricted main multiverse deb-src http://mirror.pacific.net.au/linux/ubuntu/ gutsy universe restricted main multiverse deb http://security.ubuntu.com/ubuntu/

  • the use of rails mod_rails

    Mod_rails structures based on the use of the rails running apache environment Passenger (mod_rails) is an apache-based application deployment of rails program currently supports Linux, BSD, OS X platform, not to support the windows, the installation ...

  • Understanding of JavaScript closures

    Understanding of JavaScript closures To become advanced JavaScript programmers, it is necessary to understand the closure. In this paper, ECMA 262 specification explain the closure of the internal working mechanism for JavaScript programmers understanding

  • Ruby User's Guide>> Getting started

    First, you have to check whether the installed ruby. Shell from the start (here "%" express, do not play the%), into the (-V enable ruby interpreter print version), then press Enter. If the ruby has been installed, you will see the followin ...

  • RHEL as 4 environment to install lighttpd

    In reference Robbin "in the Linux platform to install and configure Ruby on Rails explain" after the RHEL environment a try, and configure successfully. step 1: check whether the system is installed to support the library pcre # Rpm-qa | gr ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries