Deep understanding of shared memory for inter-process communication and deep understanding of processes

Source: Internet
Author: User

Deep understanding of shared memory for inter-process communication and deep understanding of processes

Shared memory is the most useful communication method between processes and the fastest IPC format. It is designed to reduce the running efficiency of other communication mechanisms. The shared memory of two different processes A and B means that the same physical memory is mapped to the process address space of process A and process B. Process A can immediately see the updates to data in the shared memory of process B, and vice versa. Because multiple processes share the same memory area, a synchronization mechanism is required. mutex locks and semaphores can both be used.

One obvious advantage of using shared memory communication is high efficiency, because the process can directly read and write the memory without any data copying. For communication methods such as photo channels and message queues, You need to copy data four times in the kernel and user space, while the shared memory only copies data twice [1]: one from the input file to the shared memory area, and the other from the shared memory area to the output file. In fact, during Memory sharing between processes, the ing is not always removed after a small amount of data is read and written. When there is new communication, the shared memory area is re-established. Instead, keep the shared area until the communication is complete. In this way, the data content is stored in the shared memory and not written back to the file. The content in the shared memory is often written back to the file when the ing is removed. Therefore, the efficiency of communication with shared memory is very high.

Principle of System V shared memory

Data to be shared between processes is stored in a region called IPC shared memory, all processes that need to access the shared area map the shared area to the address space of the process. System V shared memory obtains or creates an IPC shared memory area through shmget and returns the corresponding identifier. When the kernel ensures that shmget obtains or creates a shared memory area, initializes the shmid_kernel struct in the shared memory area, it also creates and opens a file with the same name in the shm of a special file system, and establish the corresponding dentry and inode structure of the file in the memory. The newly opened file does not belong to any process (any process can access the shared memory zone ). All of this is done by the system calling shmget.

Note: Each shared memory area has a control structure, struct shmid_kernel. shmid_kernel is a very important data structure in the shared memory area. It serves as a bridge between storage management and file systems, definition:

struct shmid_kernel /* private to the kernel */{        struct kern_ipc_perm shm_perm; /* operation permission structure */    struct file *shm_file; /* pointer in kernel */    unsigned long shm_nattch; /* number of current attaches */    unsigned long shm_segsz; /* size of segment in bytes */    time_t shm_atim; /* last-attach time */    time_t shm_dtim; /* last-detach time */    time_t shm_ctim; /* last-change time */    pid_t shm_cprid; /* pid of creator */    pid_t shm_lprid; /* pid of last shmop() */};

 

  

Like message queues and traffic signals, the kernel maintains all the shared memory areas in the system through the data structure struct ipc_ids shm_ids. The shm_ids.entries variable in points to an ipc_id structure array, and each ipc_id structure array has a pointer to the kern_ipc_perm structure. Readers should be familiar with this. For the System V shared memory area, the host of kern_ipc_perm is the shmid_kernel structure, and shmid_kernel is used to describe a shared memory area, in this way, the kernel can control all the shared areas of the system. At the same time, in the shmid_kernel structure, the file type pointer shm_file points to the corresponding file in the shm file system, so that the shared memory area corresponds to the file in the shm file system.

After creating a shared memory area, you need to map it to the process address space. The system calls shmat () to complete this function. When shmget () is called, a file with the same name in the file system shm has been created, which corresponds to the shared memory region. Therefore, the shmat () the process is equivalent to the file process with the same name in the shm of the ing file system. The principle is similar to that of mmap.

System V shared memory API
Header file:
# Include <sys/ipc. h>
    # Include <sys/shm. h>

Shmget () is used to obtain the ID of the shared memory area. If the specified shared area does not exist, a corresponding area is created. Shmat () maps the shared memory area to the address space of the calling process, so that the process can conveniently access the shared area. The shmdt () call is used to remove the process's ing to the shared memory area. Shmctl controls the shared memory area.

System V shared memory limit

In the/proc/sys/kernel/directory, record the limits of the system V shared memory, such as the maximum number of bytes in a shared memory area shmmax, shmmni, the maximum number of identifiers in the shared memory area, can be adjusted manually, but this is not recommended.

System V shared memory example/***** testwrite. c *******/# include <sys/ipc. h> # include <sys/shm. h> # include <sys/types. h> # include <unistd. h> typedef struct {char name [4]; int age;} people; main (int argc, char ** argv) {int shm_id, I; key_t key; char temp; people * p_map; char * name = "/dev/shm/myshm2"; key = ftok (name, 0); if (key =-1) perror ("ftok error"); shm_id = shmget (key, 4096, IPC_CREAT); if (shm_id =-1) {perror ("shmget error"); return ;} p_map = (people *) shmat (shm_id, NULL, 0); temp = 'a'; for (I = 0; I <10; I ++) {temp + = 1; memcpy (* (p_map + I )). name, & temp, 1); (* (p_map + I )). age = 20 + I;} if (shmdt (p_map) =-1) perror ("detach error");}/*********** testread. c *************/# include <sys/ipc. h> # include <sys/shm. h> # include <sys/types. h> # include <unistd. h> typedef struct {char name [4]; int age;} people; main (int argc, char ** argv) {int shm_id, I; key_t key; people * p_map; char * name = "/dev/shm/myshm2"; key = ftok (name, 0); if (key =-1) perror ("ftok error "); shm_id = shmget (key, 4096, IPC_CREAT); if (shm_id =-1) {perror ("shmget error"); return;} p_map = (people *) shmat (shm_id, NULL, 0); for (I = 0; I <10; I ++) {printf ("name: % s \ n ", (* (p_map + I )). name); printf ("age % d \ n", (* (p_map + I )). age);} if (shmdt (p_map) =-1) perror ("detach error ");}View Code

  

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.