Inter-process communication in Linux (2) signal (lower)

Source: Internet
Author: User
Tags posix
Inter-process communication in Linux environment (2): Signal (lower)

I. Signal Lifecycle

The signal is sent to the signal processing function after execution.

For a complete signal Life Cycle (after the signal is sent to the corresponding processing function for execution), it can be divided into three important stages, which are characterized by four important events: signal generation; signal registration completed in the process; signal cancellation completed in the process; signal processing function completed. The interval between two adjacent events forms a stage of the signal life cycle.

The following describes the practical significance of the four events:

  1. Signal "birth ". The emergence of signals refers to the occurrence of events that trigger signals (such as hardware exceptions, Timer timeouts, and call of the signal sending function kill () or sigqueue ).
  2. The signal is "registered" in the target process; The task_struct structure of the process contains data members with pending signals in the process:

Struct sigpending pending:

Struct sigpending {

Struct sigqueue * head, ** tail;

Sigset_t signal;

};

The Third Member is all pending signal sets in the process. The first and second members point to the beginning and end of a sigqueue-type structure chain (called "pending signal information chain, each sigqueue structure in the information chain depicts the information carried by a specific signal and points to the next sigqueue structure:

Struct sigqueue {

Struct sigqueue * next;

Siginfo_t Info;

}

Signal registration means that the signal value is added to the pending Signal Set of the process (sigset_t signal, the second member of the sigpending structure ), the information carried by the signal is retained to a sigqueue structure of the pending signal information chain. As long as the signal is in the pending Signal Set of the process, it indicates that the process already knows the existence of the signal, but it has not been processed yet, or the signal is blocked by the process.

Note:
When a real-time signal is sent to a process, no matter whether the signal has been registered in the process or not, it will be re-registered. Therefore, the signal will not be lost, real-time signals are also called "reliable signals ". This means that the same real-time signal can occupy multiple sigqueue structures in the pending signal information chain of the same process (each process receives a real-time signal, A structure will be allocated for it to register the signal information, and the structure will be added at the end of the pending signal chain, that is, all generated real-time signals will be registered in the target process );

When a non-real-time signal is sent to a process, if the signal has been registered in the process, the signal will be discarded, resulting in signal loss. Therefore, non-real-time signals are also called "unreliable signals ". This means that the same non-real-time signal occupies at most one sigqueue structure in the pending signal information chain of the process (after a non-real-time signal is generated, (1) if the same signal has been registered in the target structure, it will not be registered. For a process, it is equivalent to not knowing that the current signal occurs and the signal is lost; (2), if the process's pending signals do not have the same signal, register yourself in the process ).

  1. The logout of the signal in the process. During the execution of the target process, the system checks whether a signal is waiting for processing (this is done every time the system space is returned to the user space ). If a pending signal is waiting for processing and the signal is not blocked by the process, the process will unload the structure occupied by the signal in the pending signal chain before running the corresponding signal processing function. Whether to delete signals from pending processes is different from real-time and non-real-time signals. For non-real-time signals, because only one sigqueue structure is occupied in the pending signal information chain, after the structure is released, the signal should be deleted in the pending Signal Set (the signal is canceled). For real-time signals, multiple sigqueue structures may be occupied in the pending signal information chain.
    Difference in the number of components: if only one sigqueue structure is used (the process only receives the signal once), the signal should be deleted from the pending signal (the signal is canceled ). Otherwise, the signal should not be deleted from the pending Signal Set of the process (the signal cancellation is completed ).

    Before a process executes a signal processing function, it must first cancel the signal in the process.
  2. The signal life ends. After the process cancels the signal, immediately execute the corresponding signal processing function. After the execution is complete, the effect of this sending of the signal on the process is completely ended.

Note:
1) whether the signal is registered is unrelated to the function of sending the signal (such as kill () or sigqueue () and the function of signal installation (signal () and sigaction, it is only related to the signal value (signals with a signal value smaller than sigrtmin can be registered only once at most. signals with a signal value between sigrtmin and sigrtmax are registered as long as they are received by the process ).

2) when the signal is canceled to the corresponding signal processing function, if the process receives the same signal multiple times, the real-time signal will be registered in the process each time; for non-real-time signals, no matter how many signals are received, only one signal is received and registered only once in the process.

Back to Top

2. Precautions for signal Programming

  1. Prevents Loss of signals that should not be lost. If you have a deep understanding of the signal lifecycle mentioned in section 8, it is easy to know if the signal will be lost and where it will be lost.
  2. Program portability
    Considering the portability of the program, POSIX signal functions should be used as much as possible. POSIX signal functions are mainly divided into two types:

    • POSIX 1003.1 signal functions: Kill (), sigaction (), sigaddset (), sigdelset (), sigemptyset (), sigfillset (), sigismember (), sigpending (), sigprocmask () and sigsuspend ().
    • POSIX 1003.1b signal function. POSIX 1003.1b expands POSIX 1003.1 in terms of real-time signal, including the following functions: sigqueue (), sigtimedwait (), and sigwaitinfo (). Among them, sigqueue is mainly for signal sending, while sigtimedwait and sigwaitinfo () are mainly used to replace the sigsuspend () function, followed by corresponding instances.

# Include <signal. h>

Int sigwaitinfo (sigset_t * Set, siginfo_t * info ).

Similar to sigsuspend (), this function blocks a process until a specific signal occurs, but does not execute the signal processing function when the signal arrives, but returns the signal value. Therefore, in order to avoid executing the corresponding signal processing function, the process must be blocked before calling the function. Therefore, the typical code for calling this function is:

Sigset_t newmask;

Int rcvd_sig;

Siginfo_t Info;

Sigemptyset (& newmask );

Sigaddset (& newmask, sigrtmin );

Sigprocmask (sig_block, & newmask, null );

Rcvd_sig = sigwaitinfo (& newmask, & info)

If (rcvd_sig =-1 ){

..

}

If the call is successful, a signal value is returned. Otherwise,-1 is returned. The sigtimedwait () function is similar, but it increases the waiting time of a process.

  1. Program stability.
    To enhance the stability of the program, the reentrant function should be used in the signal processing function.

The reentrant (reentrant) function should be used in the signal processing program (note: the so-called reentrant function is a process that can be called by multiple tasks, when a task is called, do not worry about data errors ). After receiving the signal, the process jumps to the signal processing function and runs it. If the non-reentrant function is used in the signal processing function, the signal processing function may modify the data that should not be modified in the original process, in this way, when the process returns and then executes from the signal processing function, unexpected consequences may occur. Non-reentrant functions are considered unsafe functions in signal processing functions.

Most functions that meet the following conditions are not reentrant: (1) use static data structures, such as getlogin (), gmtime (), getgrgid (), getgrnam (), getpwuid () and getpwnam (). (2) The malloc () or free () function is called during function implementation. (3) The standard I/O function is used for implementation. The open group considers the following functions as reentrant:

_ Exit (), access (), alarm (), cfgetispeed (), cfgetospeed (), cfsetispeed (), cfsetospeed (), chdir (), chmod (), chown (), close (), creat (), DUP (), dup2 (), execle (), execve (), fcntl (), fork (), fpathconf (), fstat (), fsync (), getegid (), geteuid (), getgid (), getgroups (), getpgrp (), getpid (), getppid (), getuid (),
Kill (), Link (), lseek (), mkdir (), mkfifo (), open (), pathconf (), pause (), pipe (), raise (), read (), rename (), rmdir (), setgid (), setpgid (), setsid (), setuid (), sigaction (), sigaddset (), sigdelset (), sigemptyset (), sigfillset (), sigismember (), signal (), sigpending (), sigprocmask (), sigsuspend (), sleep (),
Stat (), sysconf (), tcdrain (), tcflow (), tcflush (), tcgetattr (), tcgetpgrp (), tcsendbreak (), tcsetattr (), tcsetpgrp (), time (), times (), umask (), uname (), unlink (), utime (), wait (), waitpid (), write ().

Even if the signal processing functions use "security functions", you must also note that when entering the processing function, you must first save the errno value and restore the original value at the end. Because the errno value may be changed at any time during signal processing. In addition, longjmp () and siglongjmp () are not listed as reentrant functions, because other calls to the two functions are not guaranteed to be safe.

Back to Top

Iii. Introduction: Signal Application Example

In Linux, the signal application is not as horrible as imagined. programmers have to do at most three things:

  1. Installation signal (sigaction () is recommended ());
  2. Implement three-parameter signal processing functions, handler (INT signal, struct siginfo * info, void *);
  3. Sigqueue () is recommended for sending signals ().

In fact, for some signals, it is enough to install the signal (default or ignore the signal processing method ). Other operations may be related to the signal set.

Example 1: signal sending and Processing
Implement a signal receiving program sigreceive (where the signal is installed by sigaction ()).

# Include <signal. h>

# Include <sys/types. h>

# Include <unistd. h>

Void new_op (INT, siginfo_t *, void *);

Int main (INT argc, char ** argv)

{

Struct sigaction Act;

Int SIG;

Sig = atoi (argv [1]);

Sigemptyset (& act. sa_mask );

Act. sa_flags = sa_siginfo;

Act. sa_sigaction = new_op;

If (sigaction (SIG, & act, null) <0)

{

Printf ("Install Sigal error \ n ");

}

While (1)

{

Sleep (2 );

Printf ("Wait for the signal \ n ");

}

}

Void new_op (int signum, siginfo_t * info, void * myact)

{

Printf ("receive signal % d", SIGNUM );

Sleep (5 );

}

 

Description: The command line parameter is a signal value. If sigreceive signo & is run in the background, the ID of the process can be obtained. Assume It is a PID, then run the kill-s signo PID verification signal sending and receiving and processing on another terminal. At the same time, the queuing problem of the signal can be verified.

Note:You can use sigqueue to implement a command line signal sending program sigqueuesend. See
Appendix 1.

Example 2: Additional signal transmission information
It mainly includes two instances:

  1. Sends signals to the process itself and transmits pointer parameters;

# Include <signal. h>

# Include <sys/types. h>

# Include <unistd. h>

Void new_op (INT, siginfo_t *, void *);

Int main (INT argc, char ** argv)

{

Struct sigaction Act;

Union sigval mysigval;

Int I;

Int SIG;

Pid_t PID;

Char data [10];

Memset (data, 0, sizeof (data ));

For (I = 0; I <5; I ++)

Data [I] = '2 ';

Mysigval. sival_ptr = data;

Sig = atoi (argv [1]);

PID = getpid ();

Sigemptyset (& act. sa_mask );

Act. sa_sigaction = new_op; // three-parameter signal processing function

Act. sa_flags = sa_siginfo; // Information Transmission Switch

If (sigaction (SIG, & act, null) <0)

{

Printf ("Install Sigal error \ n ");

}

While (1)

{

Sleep (2 );

Printf ("Wait for the signal \ n ");

Sigqueue (PID, Sig, mysigval); // sends signals to the current process and transmits Additional information

}

}

Void new_op (int signum, siginfo_t * info, void * myact) // implementation of the three-parameter signal processing function

{

Int I;

For (I = 0; I <10; I ++)

{

Printf ("% C \ n", (* (char *) (* info). si_ptr) + I )));

}

Printf ("handle signal % d over;", SIGNUM );

}

 

In this example, the signal implements the transmission of additional information, and how the signal processes the information depends on the specific application.

  1. 2. Transmit Integer Parameters between different processes: Put the signal sending and receiving in 1 in two programs, and transmit Integer Parameters during the sending process.
    Signal receiving program:

# Include <signal. h>

# Include <sys/types. h>

# Include <unistd. h>

Void new_op (INT, siginfo_t *, void *);

Int main (INT argc, char ** argv)

{

Struct sigaction Act;

Int SIG;

Pid_t PID;

PID = getpid ();

Sig = atoi (argv [1]);

Sigemptyset (& act. sa_mask );

Act. sa_sigaction = new_op;

Act. sa_flags = sa_siginfo;

If (sigaction (SIG, & act, null) <0)

{

Printf ("Install Sigal error \ n ");

}

While (1)

{

Sleep (2 );

Printf ("Wait for the signal \ n ");

}

}

Void new_op (int signum, siginfo_t * info, void * myact)

{

Printf ("the int value is % d \ n", info-> si_int );

}

 

Signal sending program: The second parameter of the command line is the signal value, and the third parameter is the ID of the receiving process.

# Include <signal. h>

# Include <sys/time. h>

# Include <unistd. h>

# Include <sys/types. h>

Main (INT argc, char ** argv)

{

Pid_t PID;

Int SIGNUM;

Union sigval mysigval;

SIGNUM = atoi (argv [1]);

PID = (pid_t) atoi (argv [2]);

Mysigval. sival_int = 8; // it does not indicate the specific meaning and is only used to explain the problem.

If (sigqueue (PID, SIGNUM, mysigval) =-1)

Printf ("send error \ n ");

Sleep (2 );

}

 

Note:Two examples of instance 2 focus on transmitting information using signals. Currently, there are very few instances that transmit information via signals in Linux, but there are some in UNIX, however, the transfer is basically about passing an integer, and I haven't seen it yet. I have never implemented pointer transmission between different processes (in fact more meaningful). Maybe there is a problem with the implementation method. please email me.

Example 3: signal blocking and Signal Set Operations

# Include "signal. H"

# Include "unistd. H"

Static void my_op (INT );

Main ()

{

Sigset_t new_mask, old_mask, pending_mask;

Struct sigaction Act;

Sigemptyset (& act. sa_mask );

Act. sa_flags = sa_siginfo;

Act. sa_sigaction = (void *) my_op;

If (sigaction (sigrtmin + 10, & act, null ))

Printf ("Install signal sigrtmin + 10 error \ n ");

Sigemptyset (& new_mask );

Sigaddset (& new_mask, sigrtmin + 10 );

If (sigprocmask (sig_block, & new_mask, & old_mask ))

Printf ("Block Signal sigrtmin + 10 error \ n ");

Sleep (10 );

Printf ("now begin to get pending mask and unblock sigrtmin + 10 \ n ");

If (sigpending (& pending_mask) <0)

Printf ("Get pending mask error \ n ");

If (sigismember (& pending_mask, sigrtmin + 10 ))

Printf ("signal sigrtmin + 10 is pending \ n ");

If (sigprocmask (sig_setmask, & old_mask, null) <0)

Printf ("unblock signal error \ n ");

Printf ("signal unblocked \ n ");

Sleep (10 );

}

Static void my_op (int signum)

{

Printf ("receive signal % d \ n", SIGNUM );

}

 

Compile the program and run it later. Send a signal to the process on another terminal (run kill-s 42 PID, sigrtmin + 10 is 42). Check the running mechanism of several key functions, signal Set-related operations are relatively simple.

Note:In the above examples, the printf () function is used only as a diagnostic tool. The pringf () function cannot be reentrant and should not be used in signal processing functions.

Back to Top

Conclusion:

I have benefited a lot from systematically analyzing and summarizing the Linux signal mechanism! Thank you for your support!
Comments and suggestions are greatly welcome!

Back to Top

Appendix 1:

The command line signal sending program sigqueuesend implemented by sigqueue. The second parameter of the command line is the sent signal value, and the third parameter is the process ID that receives the signal. It can be used with instance 1:

# Include <signal. h>

# Include <sys/types. h>

# Include <unistd. h>

Int main (INT argc, char ** argv)

{

Pid_t PID;

Int SIG;

Sig = atoi (argv [1]);

PID = atoi (argv [2]);

Sigqueue (PID, Sig, null );

Sleep (2 );

}

 

References

  • Linux kernel source code scenario analysis (I): Mao decao, Hu Ximing, Zhejiang University Press, the best reference materials to verify a conclusion and idea;
  • Advanced Programming in UNIX environments; Author: W. Richard Steven s; Translator: Yu jinyuan; Mechanical Industry Press. The development process of the signal mechanism is described in detail.
  • Signal, sigaction, kill, and other manuals are the most direct and reliable references.
  • Http://www.linuxjournal.com/modules.php? OP = modload & name = NS-Help & file = man provides online guidance for many system calls and library functions.
  • Http://www.opengroup.org/onlinepubs/007904975/you can query many key functions (including system calls) Here, a very good website.
  • Http://unix.org/whitepapers/reentrant.htmlto repeat the role.
  • Http://www.uccs.edu /~ Compsvcs/doc-CDROM/docs/html/aps33dte/docu_006.htm provides a good description of real-time signals.

About the author

Zheng yanxing, a doctorate degree from the National Defense University. Contact info:
Mlinux@163.com.

 

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: 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.