Simple Analysis of Process Communication Methods in Linux

Source: Internet
Author: User

The process communication methods in Linux are basically inherited from the process communication methods on the UNIX platform. The Bell Labs and BSD (Berkeley Software release center at the University of California Berkeley), which have contributed significantly to the development of UNIX, have different emphasis on inter-process communication. The former improves and expands the inter-process communication methods in the early days of UNIX to form a "System v ipc", and the communication process is limited to a single computer; the latter skips this restriction and forms a socket-based inter-process communication mechanism. In Linux, the two are inherited, as shown in:

Among them, the original Unix IPC includes: Pipeline, FIFO, signal; System v ipc includes: System V message queue, System V signal light, System V shared memory zone; posix ipc includes: POSIX message queue, POSIX signal lamp, and POSIX shared memory zone. There are two points to explain: 1) due to the diversity of UNIX versions, the Institute of electronic and electrical engineering (IEEE) developed an independent UNIX standard, this new ansi unix standard is called the portable operating system interface (psoix) in the computer environment ). Most of the existing UNIX and popular versions follow the POSIX standard, while Linux has followed the POSIX standard from the very beginning; 2) BSD is not involved in inter-process communication within a single machine (socket itself can be used for inter-process communication within a single machine ). In fact, many UNIX versions of Single-host IPC have traces of BSD, such as the anonymous memory ing supported by 4.4bsd and the realization of reliable signal semantics by 4.3 + BSD.

Figure 1 shows the various IPC methods supported by Linux. In the subsequent discussions in this article, in order to avoid conceptual confusion, we should try to mention as few UNIX versions as possible, the discussion of all issues will eventually come down to inter-process communication in the Linux environment. In addition, Linux supports different implementation versions of communication methods (for example, POSIX shared memory and System V shared memory ), this section mainly introduces POSIX APIs.

Introduction to several main methods for inter-process communication in Linux:

  1. Pipeline (PIPE) and famous Pipeline (Named Pipe): pipeline can be used for communications between kinship processes. Famous pipelines overcome the pipe's no-name restrictions. Therefore, in addition to the functions of pipelines, it also allows communication between unrelated processes;
  2. Signal: a signal is a complex communication method used to notify the receiving process of an event. In addition to inter-process communication, the process can also send a signal to the process itself; in addition to the early UNIX signal semantic function Sigal, Linux also supports the signal function sigaction whose semantics complies with the posix.1 standard (in fact, this function is based on BSD, BSD in order to achieve reliable signal mechanism, it can also unify external interfaces and implement the signal function again using the sigaction function );
  3. Message Queue: A chain table of messages, including the POSIX Message Queue System V message queue. A process with sufficient permissions can add messages to the queue. A process with the read permission can read messages from the queue. The message queue overcomes the disadvantages of low signal carrying information, and the pipeline can only carry unformatted byte streams and limited buffer size.
  4. Shared Memory: Allows multiple processes to access the same memory space. It is the fastest available IPC format. It is designed to reduce the running efficiency of other communication mechanisms. It is often used in conjunction with other communication mechanisms, such as semaphores, to achieve synchronization and mutual exclusion between processes.
  5. Semaphore (semaphore) is mainly used for synchronization between processes and between different threads of the same process.
  6. Socket: a more general inter-process communication mechanism that can be used for inter-process communication between different machines. It was initially developed by the BSD branch of the UNIX system, but now it can be transplanted to other UNIX-like systems: both Linux and System V variants support sockets.

----. MPS queue

The pipeline is the oldest method of inter-process communication. It includes two types: anonymous pipeline and famous pipeline. The former can be used for inter-process communication with kinship, it can be used for communication between the parent process and the child process. The latter overcomes the restriction that the MPs queue has no name. Therefore, in addition to the functions of the former, it also allows communication between unrelated processes and can be used for communication between any two processes running on the same machine.
The unknown pipeline is created by the pipe () function:

# Include <unistd. h>
Int pipe (INT filedis [2]);

The filedis parameter returns two file descriptors: filedes [0] is read and filedes [1] is write. Output of filedes [1] is the input of filedes [0.

In Linux, famous pipelines can be created in two ways: Command Line mknod System Call and function mkfifo. The following two channels generate a famous pipe named myfifo under the current directory:

Method 1: mkfifo ("myfifo", "RW ");

Method 2: mknod myfifo P

After a famous pipeline is generated, you can use common file I/O functions such as open, close, read, and write to operate it.

 

---- Message Queue

Message Queue is a chain table of messages, including POSIX Message Queue System V message queue. Message Queue is used for communication between processes running on the same machine. It is similar to the pipeline. A process with sufficient permissions can add messages to the queue, A process with read permission can read messages in the queue. The message queue overcomes the disadvantages of low signal carrying information, and the pipeline can only carry unformatted byte streams and limited buffer size. We can replace it with a Stream pipeline or a set of interfaces.

 

---- Shared memory

Shared memory is the fastest way to communicate between processes running on the same machine, because data does not need to be copied between different processes. A shared memory area is usually created by a process, and other processes read and write this memory area. Shared Memory is often used in conjunction with other communication mechanisms, such as semaphores, to achieve synchronization and mutual exclusion between processes.
The first function to use is shmget, which obtains a shared storage identifier.

Main operation functions:
Create semaphores
Int semget (
Key_t key, // The Key to identify the semaphore, there are three methods: 1, use the IPC--PRIVATE to let the system generate, 2, select a random number, 3, use ftok to generate from the file path name
Int nsemes, // number of elements in the semaphore set
Int flag // ipc_creat and ipc_excl are created only when the semaphore set does not exist.
)
Success: return the semaphore handle.
Failed:-1 is returned.

This function is similar to the familiar malloc function. The system allocates the size of memory as the shared memory according to the request. In the Linux kernel, each IPC structure has a non-negative integer identifier, So that you only need to reference the identifier when sending a message to a message queue. This identifier is obtained by the key word of the IPC structure in the kernel. This keyword is the key of the first function above. The data type key_t is defined in the header file SYS/types. H. It is a long integer data. In our subsequent chapters, we will also encounter this keyword.

Use the ftok function to generate a keyword Based on the file path name.
Key_t ftok (const char * pathname, int proj_id );
The path name must have the corresponding Permissions
Control semaphores
Int semctl (
Int Semid, // semaphore set handle

Int semnum, // number of elements in the semaphore set
Int cmd, // command/* Union senum Arg */)

Success: the corresponding value is returned.
Failed:-1 is returned.
Command details:
CMD: ipc_rmid: deletes a semaphore.
Ipc_excl is created only when the semaphore set does not exist.
Ipc_set: Set the semaphore permission
Setval: set the value of the element of the specified semaphore to AGC. Val.
Getval obtains the value of a specified semaphore.
Getpid obtains the final process ID that finally controls this element.
Getncnt obtains the number of processes that wait for the element to change to 1.
Getzcnt obtains the number of processes that wait for the element to change to 0.

After the shared memory is created, other processes can call shmat () to connect it to their own address space.

Void * shmat (INT shmid, void * ADDR, int flag );

Shmid is the shared storage identifier returned by the shmget function. The ADDR and flag parameters determine how to determine the connection address. the return value of the function is the actual address connected to the Data Segment of the process, A process can perform read/write operations on the process.

When using shared storage to implement inter-process communication, note the synchronization of data access. Make sure that the desired data has been written when a process reads data. Generally, semaphores are used to synchronize access to shared storage data. In addition, you can use the shmctl function to set some flags of shared storage memory, such as shm_lock and shm_unlock.

 

---- Semaphores

Semaphores, also known as semaphores, are used to coordinate data objects between different processes. The most important application is the shared memory mode of inter-process communication in the previous section. Essentially, semaphores are a counter used to record access to a resource (such as shared memory. Generally, to obtain shared resources, the process must perform the following operations:

(1) Test the semaphore that controls the resource.

(2) If the semaphore value is positive, the resource can be used. The process minus 1.

(3) If the semaphore is 0, the resource is currently unavailable, and the process enters the sleep state until the signal value is greater than 0. The process is awakened and transferred to step (1 ).

(4) When a process no longer uses a semaphore-controlled resource, the signal value is increased by 1. If a process is sleeping and waiting for this semaphore at this time, it will be awakened.

The Linux Kernel Operating system rather than the user process is used to maintain the semaphore state. We can see the definition of each structure used by the kernel to maintain the semaphore state from the/usr/src/Linux/include/Linux/SEM. h file. Semaphores are a set of data. You can use each element of this set separately. The first function to be called is semget, which is used to obtain a semaphore ID.
Int semget (key_t key, int nsems, int flag );

The key is the keyword of the IPC structure discussed earlier. It will decide whether to create a new semaphore set or reference an existing semaphore set in the future. Nsems is the number of semaphores in the set. If you create a new set (generally on the server), you must specify nsems. If you reference an existing set of semaphores (usually on the client), you can specify nsems as 0.

The semctl function is used to operate on semaphores.

Int semctl (INT Semid, int semnum, int cmd, Union semun Arg );

Different operations are implemented through the CMD parameter. Seven different operations are defined in the header file Sem. H. You can refer to the actual programming.

The semop function automatically executes the operation array on the semaphore set.

Int semop (INT Semid, struct sembuf semoparray [], size_t NOPs );

Semoparray is a pointer that points to an array of semaphore operations. NOPs specifies the number of operations in the array.

Next, let's look at a specific example. It creates a keyword for a specific IPC structure and a semaphore, creates an index for this semaphore, and modifies the semaphore value pointed to by the index, finally, we clear the semaphore.

----. Socket

Socket programming is one of the main ways to implement inter-process communication between Linux and most other operating systems. The well-known WWW Service, FTP service, and Telnet service are implemented based on a set of interface programming. In addition to remote computer processes, the set of interfaces also apply to inter-process communication within the same local computer.

 

Generally, processes in Linux contain the following key elements:

  • There is an executable program;
  • Dedicated system stack space;
  • The kernel contains its control block (Process Control Block), which describes the resources occupied by the process so that the process can be scheduled by the kernel;
  • Independent storage space

Sometimes processes and threads are not completely differentiated, but they are often understood according to the context.

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.