Implement internal process Communication in Linux

Source: Internet
Author: User

Linux provides a variety of internal process communication mechanisms, including shared memory, memory ing files, first-in-first-out (FIFO), interfaces (sockets), and a variety of identity for synchronization. In this article, we will mainly discuss the technology of shared memory and memory ing files.

In general, interprocess communication (IPC) refers to communication between two or more processes and two or more threads. Each IPC Mechanism has different strengths or weaknesses, but no IPC Mechanism contains built-in Synchronization Methods. Therefore, programmers not only need to implement synchronization in their own programs, but also need to develop their own communication protocols to use the IPC Mechanism.

Shared Memory

Use shared memory and usageMallocTo allocate memory areas is very similar. The method for using shared memory is:

1. Use shmget to allocate memory areas for a process/thread.

2. Use shmat to place one or more processes/threads in the shared memory. You can also use shmctl to obtain information or control the shared area.

3. Use shmdt to separate from the shared area.

4. Use shmctl to unallocate Space

The following is an example:

// Create a shared memory area
Intshared_id;
Char * region;
Const intshm_size = 1024;

Shared_id = shmget (ipc_private, // ensure that a unique ID is used
Shm_size,
Ipc_creat | ipc_excl | // create a new memory area
S_irusr | s_iwusr); // enables the current user to read and write data to this region.

// Cross process or generate process.


// Add the newly created memory area to the process/thread
Region = (char *) shmat (segment_id, 0, 0 );

// Other program code
...

// Separate processes/threads
Shmdt (region );

// Destroy the shared memory area
Shmctl (shared_id, ipc_rmid, 0 );

Shared memory is the fastest IPC method in Linux. It is also a two-way process. Any process in the shared area can read and write the memory. The disadvantage of this mechanism is that its synchronization and Protocol are not controlled by programmers. You must ensure that the handle is passed to sub-processes and threads.

Memory ing File

The memory ing file is not only used for IPC, but also plays a major role in other processes. If you need to initialize an allocated buffer to zero, just remember/Dev/zero. You can also map files to the memory to improve its performance. It allows you to read and write files like reading and writing strings. The following is an example:

Const char filename [] = "testfile ";
Intfd;
Char * mapped_mem;
Const intflength = 1024;
FD = open (filename, o_rdwr | o_creat, s_irusr | s_iwusr );
Lseek (FD, flength + 1, seek_set );
Write (FD, "\ 0", 1 );
Lseek (FD, 0, seek_set );

Mapped_mem = MMAP (0,
Flength,
Prot_write, // allow write
Map_shared, // The written content is immediately written to the file
FD,
0 );

Close (FD );

// Use the ing area.
...

Munmap (file_memory, flength );

The advantage of using memory ing to process IPC is that you don't need to process handles throughout the process: You just need to open the file and map it to the appropriate location. You can use a memory ing file between two unrelated processes.

The disadvantage of using memory ing is that the speed is not as fast as that of shared memory. If the file size is large, the required virtual memory size will be large, resulting in a reduction in overall performance.

Text author Mike Owens is a software engineer for allscripts healthcare solutions. He has been in the software industry for more than eight years.
Bytes ---------------------------------------------------------------------------------------------------------------------------
The process communication methods in Linux are basically inherited from the process communication methods on the UNIX platform.

Collation

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 );

Message Queue: A chain table of messages, including the POSIX Message Queue systemv 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.

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.

Semaphore (semaphore) is mainly used for synchronization between processes and between different threads of the same process.

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.

The following describes the communication mechanism.

Appendix 1: References [2] briefly describe processes in Linux:

Generally, processes in Linux contain the following key elements:

1. There is an executable program;
2. Dedicated system stack space;
3. 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;
4. Independent storage space
5. The process and thread are sometimes not fully differentiated, but often understood according to the context.
References:

1. Advanced Programming in UNIX environments; Author: W. Richard Steven s; Translator: Yu jinyuan; Mechanical Industry Press. It has rich programming instances and key functions along with the development of UNIX. Linux kernel source code Scene Analysis (up and down), Mao decao, Hu Ximing, Zhejiang University Press, provides a very good analysis of the Linux kernel. At the same time, the background of some key concepts is described in detail.

2. Second volume of UNIX Network Programming: inter-process communication; Author: W. Richard Steven s; Translator: Yang jizhang; Tsinghua University Press. A book that comprehensively describes inter-process communication in a Unix environment (there is no signal or set of interfaces, set of interfaces in the first volume ).

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.