———— of Linux signals

Source: Internet
Author: User
Tags set time sigint signal sleep function terminates

I. Signal

We run a program under the shell, can be in the process is running when the keyboard input CTRL + C, you will see that the process has been terminated, in fact, when we type CTRL + C is to send a SIGINT signal to the process, When a hardware interrupt occurs, the system will switch from executing the code to the kernel to handle the signal, while the default processing action of this signal is to terminate the process, so the running process will be terminated. Like SIGINT is a signal defined in the system, there are other signals that can be viewed through the kill-l command:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/7F/BE/wKioL1crM13z0sd0AAAfNHrFbKU101.png "title=" Sig.png "alt=" Wkiol1crm13z0sd0aaafnhrfbku101.png "/>

In the case of a variety of signals from 1 to 64, but the 32 and 33rd signals are not, so there are 62 signals in the system, of which 1 to 31st is the normal signal in the system, and 34 to 64 is a real-time signal, which is not discussed here.


-------------------------------------------------------------------------------------------


Two. Generation of signals

So, how did the signals above come about?

    • First, is generated by the terminal input, like the chestnut just lifted, from the keyboard input a command is actually sent to a process to send a specific signal, but like CTRL + C This command can only be sent to the foreground process, the background process is not working, a shell can run a foreground process and multiple background processes;

    • Second, a system function can be called to send a signal to a process, such as the KILL command actually terminates a process, but the KILL command is implemented by invoking the Kill function, which can send a specific signal to a specified process with the following command:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/7F/BF/wKioL1crQIXyMiBgAAAFKGjcA6s428.png "style=" float: none; "title=" Killfun.png "alt=" Wkiol1crqixymibgaaafkgjca6s428.png "/>

In the above command, signal is to specify the signal to be sent, can be the name of the signal can also be the image above each signal in front of the code number, and the PID signal to send the process of the PID number;

The following can write a dead loop program and run in the background, when the CTRL + C to the background process does not work, you can use the KILL command to send the specified process signal number 2nd is the SIGINT signal is CTRL + C, the signal processing mode is the default is to terminate a process:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7F/C1/wKiom1crP6_jWHANAAAeLq0SCZs928.png "style=" float: none; "title=" Kill.png "alt=" Wkiom1crp6_jwhanaaaelq0sczs928.png "/>

When you enter a line of command "Kill-2 6156" When you click the carriage return is not the result, because when you press Enter the first step back to bash wait for the user to enter the next command, here do not want the result of the command and the user entered the next command to create conflicting display disorder, So press two to enter to see the result of the process being interrupted;

In addition to the KILL function, there is a function raise function, which can send a signal to the current process, that is, to send themselves a signal, both functions are successful return 0, failed to return 1:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/7F/C1/wKiom1crQmLRS-LUAAAFghYb-kQ256.png "title=" Raise.png "alt=" Wkiom1crqmlrs-luaaafghyb-kq256.png "/>

A similar abort function is to send a signal number 6th to the current process, which is the SIGABRT signal, which causes the process to terminate abnormally, and the Exit function will be successful and therefore has no return value;


    • There is also a signal generated by the software conditions, such as the previous talk about the anonymous pipeline, when the end of the pipeline read-write end is still continuing to write the process will receive a system sent a sigpipe signal, the default processing action is to terminate the process;

      However, here we talk about a function alarm function, which is used to set a specific number of seconds, and when the time-out of the system will send a SIGALRM signal to the process, and this signal default processing action is still the termination process:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/7F/C2/wKiom1crU-Owfce0AAAVyd6OU9g533.png "title=" Alarm.png "alt=" Wkiom1cru-owfce0aaavyd6ou9g533.png "/>

The function parameter seconds is the number of seconds to set, the return value of the function is 0, or return the number of seconds left before the alarm set, for example, when the alarm set time is not yet set to reset an alarm clock, then the original alarm will return the remaining time, and when the seconds value is 0 o'clock, indicating that the set alarm is cleared, The return value of the alarm is still the remaining number of seconds;

Chestnut Time:

#include <stdio.h> #include <unistd.h>int main () {int i = 0;    Alarm (1);    while (1) {printf ("I:%d\n", i++); } return 0;}

The above program is set an alarm clock, the time of the alarm is 1 seconds, and in this second continuous i++, when a second after the alarm clock, the system will send a SIGALRM signal to the process, the signal processing action will terminate the process;

Program Run Result:
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/7F/C4/wKiom1cry4zxGLV5AAAGyXFmAAw938.png "title=" Alarmret.png "alt=" Wkiom1cry4zxglv5aaagyxfmaaw938.png "/>

The results show that the number of self-addition in a second is 13,628 times;


-------------------------------------------------------------------------------------------


Three. How the signal is processed

In general, when a signal is generated, the system handles it in the following three ways:

    • Can ignore this signal, do not perform any action;

    • Performs the default processing action of the signal, while the default processing action of most ordinary signals is to terminate a process;

    • User-defined processing actions can be performed, which is known as signal capture (catch);


The signal is captured, that is, when the signal is generated, to perform user-defined function processing actions, and the processing function to capture a signal has signal and function sigaction:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/7F/CA/wKiom1cshTGC2dVpAAAKcpcX94s467.png "style=" float: none; "title=" Signal.png "alt=" Wkiom1cshtgc2dvpaaakcpcx94s467.png "/>

In the signal function parameter,

Signum is the representative number of the signal to be captured;

handler is a function pointer that can be a user-defined function that represents the action function to be processed by the signal;


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/7F/C8/wKioL1cshgmj5sAOAAAJTJqXHlU657.png "style=" float: none; "title=" Sigaction.png "alt=" Wkiol1cshgmj5saoaaajtjqxhlu657.png "/>

The Sigaction function also captures a signal to perform a user-defined function,

The Signum is also the signal number to be captured;

The act is a data structure that is defined as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/7F/CA/wKiom1cshTLCcKZOAAAKc4vx5m4686.png "style=" float: none; "title=" Sigactionstruct.png "alt=" Wkiom1cshtlcckzoaaakc4vx5m4686.png "/>

In the data structure, thesa_handler and signal functions are the same, and a function pointer can point to a user-defined function, when Sa_handler is assigned a value of sig_ign Indicates that the default processing action of the signal is to ignore the signal, when the assignment is SIG_DFL , the default processing action is performed, and sa_mask indicates some signals that require additional shielding, when the signal processing function returns to the original state automatically; Sa_flag represents some flags to modify the behavior of the signal, which is set to 0 ,sa_sigaction represents the real-time signal processing function, not discussed here; Sa_restorer is obsolete and should not be used, POSIX does not provide the element;

oldact refers to the original data structure information of the signal, when it is not empty, it will modify the previous information to save it for later recovery;


In addition to the capture function of the two signals above, there is also a function pause, which causes the process to hang until a signal is reached, if the processing action of this number is to perform the system default processing action, then the process terminates the function does not return a value, if the signal processing action is ignored, the process will remain in a suspended state, Pause also has no chance to return; if the signal processing action is to capture the signal to perform a user-defined function, pause will error return 1 and set the error code, so the program replacement function exec is similar, only error return value;

Here is a chestnut to use the capture function of the signal, you can self-implement a sleep function:

#include  <stdio.h> #include  <signal.h>void handler (int sig)//user Custom Function {     printf ("i get a sig %d\n",  sig);} Void mysleep (unsigned int time) {    struct sigaction new,  old;//set two structural body     new.sa_handler = handler;    sigemptyset ( &new.sa_mask);     new.sa_flags = 0;    sigaction (SIGALRM ,  &new, &old);//Register signal processing function, capture SIGALRM signal     alarm (time);//Set Alarm to custom      pause ();//suspend the process until the end of the alarm to send SIGALRM signal to the process     alarm (0);//Undo Alarm      sigaction (sigalrm, &old, null);//restore the default processing action for the signal}int main () {    // In the main function to achieve is every two seconds to print a sentence "Hello world ..."     while (1)     {            mysleEP (2);//Implement mysleep        printf ("hello world...\n");     }       return 0;}

Run the program with the following results:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/7F/C8/wKioL1csjufza2iBAAA9U5ZoOj4014.png "title=" snaps. png "alt=" Wkiol1csjufza2ibaaa9u5zooj4014.png "/>


For the above process, there is an important point to explain clearly, that is how the system is to complete from the signal generated to the signal is processed by the series of actions; it needs to be known that the signal is not immediately processed, but there is an appropriate opportunity to decide whether to deal with the signal, specifically explained as:

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/7F/CB/wKiom1csk-yRKyHYAAAw2HeY48k122.png "title=" QQ picture 20160506210402.png "alt=" Wkiom1csk-yrkyhyaaaw2hey48k122.png "/>


-------------------------------------------------------------------------------------------


Four. Status of the signal

The signal from the generation to the process receives is an intermediate process, when the process receives a signal that is the signal of the recursion (delivery), and the signal from the generation to the state between the call signal pending (pending); The signal also has a status called blocking (block), that is, the signal is produced in a pending state but is not being handed down, but is blocked; it should be emphasized that the signal blocking and signal ignoring is not the same, the signal is ignored in the signal after the delivery of a way of processing, The signal block is that the signal has not yet been passed.

The status of the signal in each process of the PCB has a can be said to indicate the corresponding state of the table, when the signal is generated, the kernel will be in the process PCB block in the pending table set the corresponding signal bit, similarly, when a signal is blocked, there is also a block table to record whether the signal is blocked, There is also a handler table to record the way the signal is processed;

Because we discuss the common signal of the 1~31 system here, and whether each signal is generated (pending) is blocked can be used two states 0 and one record, in fact, similar to the 32-bit platform under an int type 32 bits of the state, where the State in the outstanding table 0 and 1 indicates whether the signal is generated, The Block table indicates whether the signal is blocked, but the signal does not interfere with the signal, and when a signal is generated it can be blocked before it is delivered, as well, if the signal is blocked does not affect whether the signal is generated, a signal is blocked, and when it is generated, it will not be passed. ; The two are not related;

Sigset_t is an open and blocking state that can be used to store signals, called signal sets. It can be considered to be composed of 32 bits, and each bit indicates whether the signal is valid and invalid, as to how the interior is stored, as a user temporarily do not care; The block signal set is also called the signal shielding word of the current signal;


and the operation function of the signal set is as follows:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7F/CB/wKiom1csnDzTt5yrAAANraYMNIw676.png "title=" Signal set function. png "alt=" Wkiom1csndztt5yraaanraymniw676.png "/>

The sigemptyset function means emptying a signal set that does not contain any valid signals;

The sigfillset function represents the placement of a signal set, which contains valid signals from all systems;

The sigaddset function indicates that a valid signal is added to a signal set;

The sigdelset function means that a valid signal is removed from a set of signals;

The return value of the sigismember function is a bool type used to determine whether a signal set contains a valid signal;

The set in the function parameter is a pointer to the sigset_t type, and Signum is the number of the signal;

It should be emphasized here that the Sigemptyset function or the Sigfillset function is required to initialize a signal set before adding or removing a valid signal using the Sigaddset function and the Sigdelset function;

The above function returns 0 successfully, and the failure returns-1;


The function Sigprocmask function can be used to modify and read the signal screen word of a process:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7F/CB/wKiom1csoWfyTmCgAAAJTgcPv2c532.png "title=" Sigprocmask.png "alt=" Wkiom1csowfytmcgaaajtgcpv2c532.png "/>

function parameters,

Set represents the set of signals to be modified;

Oldset Indicates the state of the signal set prior to modification in order to recover;

How to indicate how to modify, for Sig_block , to block a valid signal in the set signal set, and to Sig_unblock the active signal in the signal set to be unblocked, and to Sig_ When Setmask , the expression value is set;


After setting the signal screen word, it can also read the pending state of the current process signal, that is, the signal is generated or not:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/7F/CB/wKiom1cso3KgG0CAAAAVMYwuvTY668.png "title=" Sigpending.png "alt=" Wkiom1cso3kgg0caaaavmywuvty668.png "/>

The function reads out the status of the pending signal set from the kernel and saves it to the set ;


Here's a chestnut. Use the above signal set operation function:

#include  <stdio.h> #include  <signal.h>void printpending (sigset_t *p)  {     int i = 0;    for (i = 1; i <  32; ++i)     {            if (Sigismember (p, i))  //determine if the 1~31 signal is generated              printf ("1");        else             printf ("0");    }        printf ("\ n");} Int main () {    sigset_t b, p;//set two signal sets block and pending     Sigemptyset (&b);//The block signal set is initialized     sigaddset (&b, sigint);//SIGINT signal is CTRL + The signal generated by C is added to the block signal set     sigprocmask (sig_block, &b, null);//Set the signal screen word of the process, blocking SigiNT Signal     while (1)     {            sigpending (&p);//Get signal pending status of current process every 1 seconds          Printpending (&p);         sleep (1);    }        return 0;}


The above program blocked the 2nd signal is the SIGINT signal, so when typing CTRL + C, produced a SIGINT signal, but because the signal is blocked and therefore has been in the pending state and will not be recursive, every second to obtain the current process signal pending status to see if the corresponding signal is generated, To run the program:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7F/C9/wKioL1csqP6TmnZkAAAdnFIKGms145.png "title=" Ret.png "alt=" Wkiol1csqp6tmnzkaaadnfikgms145.png "/>

As you can see, the 2nd signal is generated when you type CTRL + C, and the second bit in the corresponding pending signal set is 1, indicating that signal number 2nd is the SIGINT signal generation.

Since signal number 2nd is blocked and is not processed by recursion, CTRL + C cannot terminate the program, and you can use Ctrl+\ to terminate the program.


-------------------------------------------------------------------------------------------


Five. Summary

    1. Signal generation: terminal input, call system function to send a specified signal to the process, software conditions such as errors and anomalies;

    2. Signal Processing: Ignore, perform the default processing action (usually terminate the process), perform user-defined action (capture);

    3. Status of the signal: pending, blocking, recursion, pending and blocking do not affect each other, and only the signal is in a pending state and is not blocked when it will be passed;

    4. The capture of the signal is actually between the user and the kernel switching back and forth, the user--(because of errors, exceptions or interrupts into the kernel)--The kernel--(after processing the exception to check if there is a signal to process, if captured into the user)---(after the signal processing function returned to the kernel --and the kernel--(return to the exception where you continue executing the user code)--user.



Finish


This article is from the "Knock Code good Sleep zzz" blog, please be sure to keep this source http://2627lounuo.blog.51cto.com/10696599/1770913

———— of Linux signals

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.