Summary of inter-process communication between Linux

Source: Internet
Author: User
Tags epoll semaphore sigint signal signal handler unix domain socket

Linux interprocess communication Summary 1. Pipeline

The pipeline is one of the original UNIX IPC forms supported by Linux and has the following features:

(1) The pipeline is half-duplex, the data can only flow in one direction, need to establish two pipelines when the two sides communicate;

(2) can only be used between parent-child processes or sibling processes (affinity-related processes);

(3) Separate form a separate file system: The pipeline is a file for the process at both ends of the pipe, but it is not an ordinary file, it does not belong to a file system, but is a separate file system, and only exists in memory.

(4) Read and write data: a process that writes to the pipeline is read out by the process at the other end of the pipeline. The content that is written is added to the end of the pipe buffer every time, and the data is read from the head of the buffer each time.

Creation of pipelines

#include <unistd.h>

int pipe (int fd[2])

The returned fd[0] is used for reading, fd[1] for writing. Thus, after a process has been created by pipe (), it is common to fork a child process and then communicate between the parent and child processes through the pipeline (so it is not difficult to roll out, as long as there are two processes in the relationship, where the kinship refers to have a common ancestor, you can use the pipeline to communicate).

Application of Piping:

* Shell:

The pipeline can be used for input-output redirection, which directs the output of one command directly to the input of another command. For example, when you type who│wc-l in a shell program, the shell program creates the WHO and the WC two processes and the pipelines between the two processes.

* For inter-process communication with affinity

Limitations of Piping:

* Only one-way data stream is supported;

* can only be used between processes that have affinity;

* No Name;

* The buffer of the pipeline is limited (piping exists in memory and is allocated a page size for the buffer when the pipeline is created);

* The pipeline transmits the unformatted byte stream, which requires that the reader and writer of the pipeline must agree on the format of the data beforehand.

2. Famous Pipes

A FIFO differs from a pipe in that it provides a path name associated with it, which exists in the file system as a FIFO file. Thus, even processes that do not have affinity to the FIFO creation process, as long as they can access the path, can communicate with each other through the FIFO (the process that accesses the path and the creation process of the FIFO), so that processes that are not related to FIFO can also exchange data.

Famous Pipeline creation:

int Mkfifo (const char * pathname, mode_t mode)

3. Signal

The signal is a simulation of the interrupt mechanism at the software level, in principle, a process receives a signal that the processor receives an interrupt request can be said to be the same. The signal is asynchronous, and a process does not have to wait for the signal to arrive by any action, in fact, the process does not know exactly when the signal arrives. There are two sources of signal events: hardware sources (e.g. we press keyboards or other hardware failures), software sources, the most common system functions for sending signals are kill, Raise,alarm and Setitimer, and Sigqueue functions, and software sources include operations such as illegal operations.

(1) Type of signal

Reliable signals and unreliable signals, real-time and non-real-time signals

reliable signals are real-time signals , and those inherited from UNIX systems are non-reliable signals that show up in the signal

Queuing is not supported, the signal may be lost, such as sending multiple times the same signal, the process can only be received once. Signal values less than sigrtmin are non-reliable signals.

A non-reliable signal is a non-real-time signal later, Linux improved the signaling mechanism, adding 32 new signals, these letters

Numbers are reliable signals, expressed in the signal support queue, not lost, how many times, you can receive how many times. Signal value

A reliable signal is located in the [Sigrtmin, Sigrtmax] zone.

(2) Installation of the signal

Early Linux uses the system to call signal to install the signal

#include <signal.h>

void (*signal (int signum, void (*handler))) (int));

The function has two parameters, Signum specifies the signal to be installed, handler the processing function of the specified signal.

The return value of the function is a function pointer to the last installed handler

Classic Installation Method:

if (Signal (SIGINT, sig_ign)! = sig_ign) {

Signal (SIGINT, Sig_handler);

}

First obtain the last handler, if not ignore the signal, install this signal handler

Since the signal is delivered, the system automatically resets the handler as the default action, in order to make the signal during the handler processing, can still react to the subsequent signal, often in the handler first statement again call signal

Sig_handler (ing Signum)

{

/* Re-install the signal */

Signal (Signum, Sig_handler);

......

}

We know that at any point in the program, the signal can happen at any time, if the signal is reinstalled in Sig_handler

Before the signal is generated, the signal executes the default action instead of the Sig_handler. This kind of problem is not predictable.

Using the library function sigaction to install the signal

To overcome the difference between the unreliable signal and the same SVR4 and BSD, the POSIX signal is installed, and the action is held until another call is made to the sigaction to create another action, using the sigaction to install the signal. This overcomes the problem of the old signal call.

#include <signal.h>
int sigaction (int signum,const struct sigaction *act,struct sigaction*oldact));

/* Set SIGINT */

Action.sa_handler= Sig_handler;

Sigemptyset (&action.sa_mask);

Sigaddset (&action.sa_mask,sigterm);

action.sa_flags= 0;

/* Get last handler, if not ignore action, install signal */

Sigaction (Sigint,null, &old_action);

if (old_action.sa_handler! = sig_ign) {

Sigaction (SIGINT, &action, NULL);

}

Library functions implemented based on sigaction: signal

Sigaction natural and powerful, but the installation signal is very cumbersome, the current Linux signal () is implemented through the sigation () function, so even through the signal () installed signal, at the end of the signal processing function no longer need to call the signal installation function.

( 3 ) How to mask the signal

The so-called shielding, is not to prohibit the delivery of signals, but temporarily blocking the delivery of signals,

After unblocking, the signal will be delivered and will not be lost. The relevant API is

Intsigemptyset (sigset_t *set);

Intsigfillset (sigset_t *set);

Intsigaddset (sigset_t *set, int signum);

Intsigdelset (sigset_t *set, int signum);

Intsigismember (const sigset_t *set, int signum);

Intsigsuspend (const sigset_t *mask);

Intsigpending (sigset_t *set);

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

int sigprocmask (int how, const sigset_t *set, Sigset_t*oldset));

The Sigprocmask () function can operate on the signal set according to the parameter how, there are three main operations:

* Sig_block adds a set of signals to the signal set in the current blocking signal set of the process

*sig_unblock if a process blocking signal set contains a signal set pointing to the signal set, the

Blocking of the signal

*sig_setmask update process block signal set for set-pointing signal set

Signal to block the entire process:

( 4 ) The life cycle of the signal

Execution complete from signal to signal processing function

For a complete signal life cycle (from the signal to the corresponding processing function to complete the execution),

Can be divided into three important stages, these three stages are characterized by four important events:

The signal is born, the signal is registered in the process, the signal is written off in the process, and the signal processing function is completed.

The following illustrates the practical significance of the four events:

The signal "born". The birth of a signal is the occurrence of an event that triggers a signal, such as a hardware exception detected, a timer timeout, and a call to signal send letter kill () or Sigqueue ().

The signal is "registered" in the target process;

The TASK_STRUCT structure of the process has data members about the outstanding signals in this process:

Structsigpending Pending:

structsigpending{

struct Sigqueue *head, **tail;

sigset_t signal;

};

The third member is the set of all outstanding signals in the process, with the first and second members pointing to a

Sigqueue type of structure chain (referred to as the "pending Signal chain list"), the end of the chain list

Each sigqueue structure depicts the information carried by a particular signal and points to the next

Sigqueue structure:

structsigqueue{

struct Sigqueue *next;

siginfo_t info;

}

Registration of Signals

Signal registration In process refers to the signal value added to the process of the pending signal set

(The second member of the sigpending structure is sigset_t signal),

and joins the end of the pending signal chain list. As long as the signal is in the pending signal set of the process,

Indicates that the process is aware of the presence of these signals, but has not yet been processed, or the signal is blocked by the process.

When a real-time signal is sent to a process, regardless of whether the signal is already registered in the process,

will be re-registered once, so the signal will not be lost, so the real-time signal is also called "reliable signal".

This means that the same real-time signal can be added multiple times in the list of outstanding signals in the same process.

When a non-real-time signal is sent to a process, if the signal is already registered in the process,

The signal is discarded, causing the signal to be lost. Therefore, the non-real-time signal is also called "unreliable signal".

This means that the same non-real-time signal is at most a sigqueue structure in the pending signal chain list of the process.

When a non-real-time signal is born,

(1), if it is found that the same signal has been registered in the target structure, then no longer register, for the process,

It is equivalent to not knowing that the signal is happening and the signal is missing.

(2) If there is no same signal in the pending signal of the process, register itself in the process.

Logout of the signal.

During process execution, it detects if a signal waits for processing

(This check is done every time you return from system space to user space.) If there are pending

The signal waits for processing and the signal is not blocked by the process, before the corresponding signal processing function is run,

The process will offload the structure that the signal occupies in the pending signal chain. Whether to signal from the process pending signal set

The deletion is different for real-time and non-real-time signals. For non-real-time signals, due to the pending letter

Only one sigqueue structure is used in the information chain, so when the structure is released, the letter should be

The signal is deleted in the process pending signal set, and for a real-time signal, it may

The pending signal information chain occupies multiple sigqueue structures, so the sigqueue structure should be occupied

The number of different treats: if only one sigqueue structure is occupied (the process only receives the signal once),

The signal should be removed in the process's pending signal set (the signal is cancelled). Otherwise, the process should not be

The signal is removed from the pending signal set (the signal is cancelled).

The process will first log out of the process before executing the signal corresponding handler function.

Signal life is terminated.

After the process unregisters the signal, the corresponding signal processing function is executed immediately after execution,

This transmission of the signal has a complete end to the impact of the process.

4. Three ways of inter-process communication provided by System V

(1) Message Queuing

The advantage of Message Queuing over named Pipes is that 1, Message Queuing can also exist independently of the send and receive processes, eliminating the difficulties that can arise when synchronizing named Pipes for opening and closing. 2. By sending messages, you can also avoid the synchronization and blocking problems of named pipes, and do not need to provide synchronization methods by the process itself. 3. The receiving program can selectively receive data through the message type, instead of being received only by default, as in a named pipe.

(2) Signal volume

The semaphore is not the same as other processes, it mainly provides access control mechanism for inter-process shared resources. is equivalent to a flag in memory that the process can determine whether it can access certain shared resources, and the process can modify the flag. In addition to access control, it can also be used for process synchronization. The semaphore has the following two types:

Binary semaphore: The simplest form of semaphore, the value of the semaphore can only take 0 or 1, similar to the mutex.

Calculate semaphore: The value of the semaphore can take any non-negative (of course, constrained by the kernel itself).

The semaphore can only perform two operation waits and sends the signal, namely P (SV) and V (SV), their behavior is this:

P (SV): If the value of SV is greater than 0, it is reduced by 1, and if its value is zero, the execution of the process is suspended.

V (SV): If another process is suspended because it waits for the SV, let it run again, and if no process is suspended because it waits for the SV, add 1 to it.

(3) Shared memory

The fastest, most efficient way to communicate between processes, directly accessing memory between processes, rather than by transmitting data. However, using shared memory requires you to provide a synchronization mechanism.

5. Sockets (Unix domain protocol)

The socket API was originally designed for network communication, but later developed an IPC mechanism on the socket's framework, UNIX Domain socket. Although the network socket can also be used for interprocess communication with the same host (via loopback address 127.0.0.1), the UNIX Domain socket is more efficient for IPC: it does not need to go through the network protocol stack, does not need to package unpacking, calculate checksum, maintain serial number and answer, etc. , just copy the application layer data from one process to another. UNIX domain sockets, compared to TCP sockets, are twice times the speed of the same transmission host. This is because the IPC mechanism is inherently reliable communication, and network protocols are designed for unreliable communications. UNIX domain sockets also provide both stream-oriented and packet-oriented API interfaces, similar to TCP and UDP, but the message-oriented UNIX domain sockets are also reliable, and messages are neither lost nor sequenced.

It is important to note that the UNIX domain protocol represents the path name of the protocol address, not the IP address and port number of the Internet domain.

#define UNIX_PATH_MAX 108

struct Sockaddr_un

{

sa_family_t sun_family; /* Af_unix */

Char Sun_path[unix_path_max]; /*pathname * *

};

Socketpair function: Create a full-duplex flow pipeline

int socketpair (int domain, int type, intprotocol, int sv[2]);

Use Unix examples of domain protocols

* Libevent Network Library to the signal encapsulation: Libevent realizes the socket network socket interface, timer events, signal events unified monitoring, that is, unified event source. Simply put, the signal is also converted into an IO event, integrated into the libevent. Network socket interface is the actual file descriptor FD, can be directly monitored in epoll, timer events can be set Epoll timeout time for monitoring, signal generation is random, libevent network library is how to process so that can use epoll to achieve signal monitoring?

If the user wants to listen to SIGINT this signal, then in the implementation of the internal SIGINT this signal set capture function. In addition, a pipeline (pipe) is created inside the implementation, and the pipeline is added to the multiplexed IO multiplexing function. The catch function will be called when the SIGINT signal is taken. The catch function is to write a character to the pipe (this character is often equal to the signal value of the captured signal). At this point, the pipeline becomes readable, and the multi-channel IO multiplexing function detects that the pipeline becomes readable. In other words, the multi-channel IO multiplexing function detects that the SIGINT signal has occurred, which also completes the monitoring of the signal.

    1. Create a pipeline (Libevent actually uses socketpair)
    2. Create an event for the read end of this socketpair and add it to the listener of the multiplexed IO function
    3. Set the signal catch function
    4. When a signal occurs, a byte is written to the Socketpair.

Summary of inter-process communication between Linux

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.