linux--Signal

Source: Internet
Author: User
Tags sigint signal signal handler terminates

First, the signal

The signal is used to notify the process that an asynchronous event has occurred. The kernel can also send a signal to the process because of an internal event, notifying the process that an event has occurred. Note that the signal is only used to notify a process of what has happened and does not pass any data to the process.

* * View a list of system-defined signals with the kill-l command

Second, the way the signal is produced

① sends a signal to the foreground via keyboard key combination (A & can be sent to the background to run after a command)

A. The default action of the signal is to terminate the process, and the default processing action of thesigquit isto terminate the process and core dump, when the core dump is the process abnormally terminated, You can choose to save the process's user space memory data to disk, the file name is usually the core, this is called core dump, usually the program has a bug, you can use the debugger to check the core file to find out the cause of the error, the default is not allowed to produce a core file, Because the core file may contain user passwords, it is unsafe to use the ulimit command to change this restriction when developing debugging, allowing the creation of core files.

ulimit-c with command

The ulimit command alters the shell process's resource limit,test process's PCB from the shell process, so it has the same resource limit value as the shell process, which can produce Core Dump .

② sends a signal to a process by invoking a system function

The A.kill command is implemented by invoking the Kill function. The KILL function can send a specified signal to a specified process. The Raise function can send a specified signal to the current process (self-signaling itself).

int Kill (pid_t pid, int signo);

int raise (int signo);

All are successful return 0, error returned-1;

The abort function causes the current process to receive an SIGABRT signal and terminates abnormally.

void abort (void);

Like the Exit function, the Abort function is always successful, so there is no return value.

③ signals generated by software conditions

A.alarm function and SIGALRM signal

unsigned int alarm (unsigned int seconds), call alarm function can set an alarm, is to tell the kernel in senconds seconds to send the current process SIGALRM signal, the default action is to terminate the current process, The return value of the function is 0 or the number of seconds remaining for the previously set alarm time.

Third, the way to deal with the signal

① Ignore this signal

② the default processing action for performing signals, typically terminating a process

③ Capture Signal

Iv. recursion and blocking of signals

①, blocking

The actual execution signal processing action is called the Signal recursion (Delivery), the signal from produces to the recursion state, is called the Signal outstanding (Pending). A process can choose to block (block) a signal. When the blocked signal is generated, it remains in the pending state until the process has unblocked the signal and executes the recursive action. Blocking and ignoring are not the same as long as the signal is blocked will not be recursive, and ignoring is a recursive after the optional processing action.

The representation of the signal in the kernel

650) this.width=650; "src=" http://s1.51cto.com/wyfs02/M01/7F/CA/wKiom1csjbeyqP0zAADkGzD9dTs551.jpg "title=" signal. JPG "alt=" Wkiom1csjbeyqp0zaadkgzd9dts551.jpg "/>

Each signal has two flags that indicate blocking (block) and pending (pending), and a function pointer representing the processing action. When the signal is generated, the kernel sets the pending flag of the signal in the process control block until the signal is reached to clear the flag

If this signal is generated many times before the process is unblocked for a signal, the regular signal in Linux is generated several times before recursion, and the real-time signal is generated several times before the recursion can be placed in a queue in turn. Each signal has only one bit of the pending flag, not 0 that is 1, does not record how many times the signal produced, the blocking flag is also indicated. (Blank is a state, pending indicates that there is no) pending and blocking flags can be stored with the same data type sigset_t , sigset_t is called the signal set, the block signal set is also called the current process signal mask Word (Signal mask), The "shielding" here should be understood as blocking rather than ignoring.

②, Signal set operation function

#include <signal.h>

int Sigemptyset (sigset_t *set);//initialize the corresponding signal set bit bit is 0

int Sigfillset (sigset_t *set);//Initialization of the object's signal set bit bit is 1

int Sigaddset (sigset_t *set, int signo);//Add valid signal

int Sigdelset (sigset_t *set, int signo);//Delete valid signal

int Sigismember (const sigset_t *set, int signo);//Determines whether a signal set of valid signal contains a signal, contains a return of 1, does not contain return 0.

③, Sigprocmask

The call function Sigprocmask can read or change the signal mask character of the process (blocking the signal set).

int sigprocmask (int how, const sigset_t *set, sigset_t *oset), success is 0, error is-1;

If the call to Sigprocmask relieves blocking of the current number of pending signals, at least one of the signals is passed before Sigprocmask returns.

How the parameter means

The Sig_block set contains the signals we want to add to the current signal mask,

The Sig_unblock set contains signals that we want to unblock in the word from the current signal,

Sig_setmask sets the current signal screen word to the value that set points to,

④, sigpending

int sigpending (sigset_t *set);

Sigpending reads the outstanding signal set of the current process and passes through the set parameters. A successful call returns 0, and an error returns-1.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Instructions for the program

  1  #include <stdio.h>  2  #include <unistd.h>  3 # Include<signal.h>  4 void printsigset (Sigset_t* sig)   5 {   6     int i=0;  7     for (; i<31;i++)   8     {  9          if (Sigismember (sig,i))//Determines whether the specified signal is in the target set  10         {  11             printf ("1");  12          } 13          else 14         { 15              printf ("0"); 16          } 17      } 18     printf ("\ n");  19 } 20 int  main ()  21 { 22     sigset_t s,p;//defining signal sets  23      sigemptyset (&s);//Initialize  24     sigemptyset (&p);  25      sigaddset (&s,sigint);//Set Signal ctrl+c 26      Sigprocmask (sig_block,&s,null);//Set block signal set, block  sigint signal  27     while (1)  28     { 29          Sigpending (&p);//get the outstanding signal set  30         printsigset (&AMP;P);  31         sleep (1);  32     }  33     return 0; 34 }

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/7F/CB/wKiom1cslofTUwnJAAG2QcWrr-M220.jpg "title=" Sigpending. JPG "alt=" Wkiom1csloftuwnjaag2qcwrr-m220.jpg "/>

Results Analysis:

When the program runs, the pending state of each signal is printed once every second, until the ctrl-c will leave the SIGINT signal in a pending state.

V. Capturing signals

A. How the kernel achieves signal capture

If the signal processing action is a user-defined function, call this function when the signal is recursive, this is called the capture signal, the process is as follows, for example,

1. The user program registers the Sigquit signal processing function Sighandler.

2. The main function is currently executing and an interrupt or exception switch to the kernel state occurs.

3. Check that there is a signal sigquit recursion before returning to the main function of the user state after the interrupt processing is complete.

4. The kernel decides to return to the user state after not resuming the context of the main function to continue execution, but instead executes the Sighandler function, the Sighandler and main functions use different stack space, there is no call and called relationship between them, is two independent control process.

5. The Sighandler function returns and automatically executes a special system call Sigreturn again into the kernel state.

6. If there is no new signal to be reached, this time back to the user state is to restore the context of the main function to continue execution

* * (before returning to the user configuration from the User Configuration , kernel State, the signal recursion, return to the User state processing signal--processing completed before entering the kernel state, if there is no new signal recursion, return to the User state recovery context continue to execute)

B.sigaction

int sigaction (int signo, const struct sigaction *act, struct sigaction *oact);

The Sigaction function can read and modify the processing action associated with the specified signal. Successful call returns 0, error returns-1

Assigning a value of Sa_handler to a constant sig_ign to sigaction means ignoring the signal, assigning a constant SIG_DFL representing the system default action, assigning a function pointer to the signal with a custom function, or registering a signal handler function with the kernel. The function return value is void, can take an int parameter, through the parameter can know the current signal number, so you can use the same function to handle a variety of signals. Obviously, this is also a callback function, not called by the main function, but is called by the system.

When the processing function of a signal is called, the kernel automatically joins the current signal to the signal screen word of the process, and when the signal processing function returns, the original signal screen word is automatically restored, so that when a signal is processed, if the signal is generated again, it will be blocked until the current processing ends.

If the signal processing function is called, in addition to the current signal is automatically shielded, but also want to automatically block other signals, the Sa_mask field is used to illustrate these signals that require additional shielding, when the signal processing function returned automatically restore the original signal mask word.

C.pause

int pause (void);

The pause function suspends the calling process until a signal is reached. If the signal processing action is to terminate the process, then the process terminates, the pause function does not have a chance to return, if the signal processing action is ignored, the process continues to be suspended, pause does not return, if the signal processing action is capture, then call the signal processing function after pause return-1,

Functions for Sleep (3) with alarm and pause

 1  #include <stdio.h> 2  #include <unistd.h> 3  #include <signal.h>  4 void sig_alarm (Int signo)  5 { 6         //do nothing 7 } 8 unsigned int  my_sleep (unsigned  Int times)  9 { 10     struct sigaction new ,old;  11     unsigned int unslept=0; 12      New.sa_handler=sig_alarm; 13     sigemptyset (&new.sa_mask); 14      sigemptyset (&old.sa_mask); 15     new.sa_flags=0;  16     sigaction (sigalrm,&new,&old);//Registered signal processing function  17      alarm (Times),  //set alarm  18     pause (); 19      unslept=alarm (0)//Cancel alarm  20     sigaction (sigalrm,&old,null);//restore default signal processing action  21      return unslept; 22 } 23 int main ()  24 {  25     while (1)  26     { 27          my_sleep (5); 28          printf ("5 senconds pass\n"); 29     } 30      return 0; 31 }

Six, reentrant function

When a signal is captured, regardless of where the main control flow of the process is currently executing, it will first be executed in the signal handler, and then continue with the main control flow after the signal processing function returns. The signal processing function is a separate control flow because it is asynchronous with the main control flow, there is no call and called relationship, and different stack space is used. The introduction of signal processing functions allows a process to have multiple control processes, which can cause conflicts if these control processes access the same global resources (global variables, hardware resources, and so on).



linux--Signal

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.