Linux inter-process communication Linux Process basics Linux from program to process

Source: Internet
Author: User

Author: vamei Source: http://www.cnblogs.com/vamei welcome reprint, please also keep this statement. Thank you!

Thank you.NonoobError Correction

 

We have already stated in the Linux signal base that the signal can be considered as a rough inter-process communication (IPC, interprocess communicationTo pass information to the memory space closed by the process. To transfer more information between processes, we need other inter-process communication methods. The communication methods between processes can be divided into two types:

    • MPs queue(PIPE) mechanism. In the Linux text stream, we mentioned that pipelines can be used to connect the output of one process to the input of another process, so as to utilizeFile operation APITo manage inter-process communication. In Shell, we often use pipelines to connect multiple processes, so that various processes can collaborate and implement complex functions.
    • Traditional IPC(Interprocess communication ). We mainly referMessage Queue(Message Queue ),Semaphores(Semaphore ),Shared Memory(Shared memory ). These IPC features that allow multi-process sharing of resources, similar to multi-thread sharing of heap and global data. Because multi-process tasks are concurrent (each process contains one process and multiple processes have multiple threads), you must solve this problem when sharing resources.Synchronization(Refer to Linux multithreading and synchronization ).

 

1. Pipelines and FIFO files

An original IPC method is used for all processes.Communicate via a file. For example, I write my name and age on paper. Another person reads this paper and will know my name and age. He can also write his information on the same piece of paper, and when I read this piece of paper, I can also know other people's information. However, this method is inefficient because hard disk read/write is slow. So can we put this piece of paper into the memory to speed up reading and writing?

In Linux text stream, we have explained how to useMPs queueConnect multiple processes. Similarly, manyProgramming LanguageThere are also some commands used to implement similar mechanisms, such as using popen and pipe in Python sub-processes.Popen library functionsTo implement pipelines (the pipelines in shell are compiled based on this ). The pipeline is a buffer (burrer) managed by the kernel, which is equivalent to a piece of paper we put into the memory. One end of the MPs queue connects to the output of a process. This process will put information into the pipeline. The other end of the MPs queue connects to the input of a process. This process extracts the information that is put into the MPs queue. A buffer zone does not need to be large and is designedRingSo that the pipeline can be recycled. If there is no information in the pipeline, the process read from the pipeline will wait until the process at the other end is put in the information. When the pipeline is filled with information, the process that tries to put the information will wait until the process at the other end retrieves the information. When both processes are terminated, the MPs queue automatically disappears.

Pipeline utilization in principleFork MechanismEstablish (refer to Linux Process basics and Linux from program to process), so that two processes can be connected to the same pipe. At the beginning, the two arrows above were bothConnect to the same processProcess 1 (two arrows connected to process 1 ). WhenForkWhen the process is copied, the two connections are alsoCopyTo the new process (process 2 ). Then, each processCloseA connection that you don't need (two black arrows are closed; process 1 closes the input connection from pipe, and process 2 closes the connection from output to pipe). In this way, the remaining red connections constitute pipe, for example.

Based on the fork mechanism, pipelines can only be used between parent and child processes, or between two child processes with the same ancestor (Kinship between processes). To solve this problem, Linux providesFIFOConnection process. FIFO is also calledNamed Pipe(Named Pipe ).

FIFO (first in, first out) is a specialFileType, which has the corresponding path in the file system. When a process opens the file in read (r) mode and another process opens the file in write (w) mode, the kernel will establish a pipeline between the two processes, therefore, FIFO is actually managed by the kernel and does not work with hard disks. The reason is FIFO, because the pipeline is essentiallyFirst-in-first-outOfQueueData Structure: The earliest data is read first (like a conveyor belt, a cargo, and a cargo) to ensure the order of information exchange. FIFO only borrowedFile System(File system, refer to the Linux File Management Background) to name pipelines. Write mode processes write data to FIFO files, while read mode processes read data from FIFO files. WhenDelete a FIFO fileThe pipeline connection disappears. The advantage of FIFO is that we can identify pipelines through file paths, so as to establish connections between unrelated processes.

 

2. Traditional IPC

These traditional IPC instances have a long history, so their implementation methods are not perfect (for example, we need a process to delete the established IPC ). A common feature is that they do not use APIs for file operations. For any IPC, you can establish multiple connections and useKey)As a recognition method. We can use the key value in a process to specify the connection (for example, multiple message queues, and one of them is used ). Key values can be transmitted between processes in some IPC mode (for example, pipe, FIFO, or file writing), or they can be embedded in programmingProgram.

When key values are shared by several processes, these traditional IPC methods are very similar to multi-thread resource sharing (see Linux multithreading and synchronization ):

  • semaphor E and mutex is similar to . It is used to handle synchronization issues. Mutex is like a restroom that can only accommodate one person, so semaphore is like a restroom that can accommodate n people . In fact, semaphore is a count lock (I think it is very easy to confuse semaphore and signal to translate semaphore into semaphores) , which can be obtained by N processes. When more processes attempt to obtain semaphore, they must wait for the previous process to release the lock. When N is equal to 1, the functions of semaphore and mutex are identical. Many programming languages also use semaphore to handle the problem of multi-thread synchronization. A semaphore will always exist in the kernel until a process deletes it.
  • Shared MemorySimilar to multi-threaded global data sharing and heap sharing. A process can take out part of its memory space and allow other processes to read and write. When using shared memory, pay attentionSynchronization. We can use semaphore for synchronization, or create mutex or other thread synchronization variables in the shared memory for synchronization. Because the shared memory allows multiple processes to directly operate on the same memory area, it isHighest efficiency.

Message Queue(Message Queue) is similar to pipe. It also createsQueueThe messages that are first put into the queue are first taken out. The difference is that the Message Queue allowsAdd multiple processes to messagesAnd allowRetrieve messages from multiple processes. Each message can containInteger identifier(Message_type ). You can use identifiers to classify messages (in extreme cases, you can set a different identifier for each message ). When a process extracts a message from the queue, it can retrieve the message in the first-in-first-out order, or it can only retrieve the message that conforms to a certain identifier (when there are multiple such messages, in the same order ). Another difference between message queue and pipe is that it does not use file APIs. Finally, a queue does not automatically disappear, and it will remain in the kernel until a process deletes the queue.

 

Multi-Process Collaboration can help us make full use of the advantages of multi-core and the Internet. Multi-process can effectively solve the computing bottleneck problem. Internet communication is actually a problem of inter-process communication, but these processes are distributed on different computers. Network Connection is implemented through socket. Because the socket content is huge, we will not go deep here. A small annotation is that socket can also be used for communication between processes in the computer.

 

Summary:

Pipe, FIFO

Semaphore, message queue, shared memory; Key

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.