Linux interprocess communication: Shared memory

Source: Internet
Author: User

Before mentioning the Interprocess communication pipeline, Message Queuing, semaphore, and then where the semaphore is a PV operation, the manipulated is a shared resource. In the IPC module we mentioned, Message Queuing is for the data unit information transfer, the pipeline is not part of the system V IPC, so according to an operating system as a whole, he should also have a message transmission about the byte stream, and faster than before, And with the amount of semaphores we've said before, there's the concept of shared memory.

What is shared memory?

Shared memory is a way of communicating between multiple processes that share memory areas, and he is implementing memory sharing in a way that maps memory segments between multiple processes, which is the fastest way for IPC, because there is no intermediate process to communicate the way that shared memory, two pipelines, Message Queuing means that the data needs to be transformed through an intermediary mechanism.

Shared memory way directly to map a segment of memory, multiple processes of shared memory is a unified fast physical space, only a different address, so do not need to replicate, you can directly use this space.

Let's look at the shared memory-related functions under Linux:

1. Create a shared memory function:

#include <sys/ipc.h> #include <sys/shm.h>int shmget (key_t key,size_t size,int SHMFLG);

The first parameter is the value of the keyword, which is then compared to the key value of the existing de 1 other shared memory segment in the kernel, which, after comparison, relies on the 3rd parameter, as in the previous message queue.

2. Get the shared memory address function Shmat ()

The function Shmat () is used to obtain the address of the shared memory, and after a successful acquisition of shared memory, it can read and write as if it were using common memory.

#include <sys/ipc.h> #include <sys/shm.h>void* shmat (int shmid,const void *shmaddr,int shmflg); int Shmdt ( const void *SHMADDR);

If the shmaddr parameter value equals 0, the internal medicine will try to find an unmapped area where the user can specify an address, but usually the address is used only to access the hardware that is owned or to resolve conflicts with other applications. The SHM_RND flag can be manipulated with the flag parameter, and the result is set to the flag parameter. The SHM_RDONLY flag parameter is set to the or operation, and the result is set to the flag parameter, so that the mapped shared memory side smart tag is read-only.

SHMDT () is used to delete a section of shared memory, in which the value of the Shm_nattch member of the associated SHMID_DS structure is subtracted by 1 after the disconnection operation has been successfully completed. If this value is reduced to 0, the kernel will actually delete this shared memory.

4. Shared Memory control function Shmctl ()

#include <sys/ipc.h> #include <sys/shm.h>int shmctl (int shmid,int cmd,struct shmid_ds*buf);

The second parameter is: Ipc_set, which gets the SHMID_DS structure with short memory. and store it in the address specified by the BUF parameter. Sets the value of the Ipc_pern member of the memory segment Shmid_ds structure, which is obtained from the BUF parameter.

Ipc_rmid: Marks a segment of memory to be deleted. Instead of actually deleting the memory segment from memory, it simply marks the memory segment for future deletion, and the last disconnection will occur.


Here's a look at the actual code:

shm.h#pragma once#include <stdlib.h> #include  <stdio.h> #include  <sys/shm.h > #include  <sys/ipc.h> #include  <sys/types.h> #include  <sys/wait.h> #include  <unistd.h> #define  _PATH_  "." #define &NBSP;_PROJECT_&NBSP;0X777#DEFINE&NBSP;_SHM_SIZE_&NBSP;4*1024INT&NBSP;GET_SHM (); Void* at_shn (); int  delete_shm (); Int rm_shm ();//shm.c#include  "shm.h" Int get_shm () {key_t key =  ftok (_path_,_project_); if (key < 0) {perror ("Ftok"); return -1;} Int flag =ipc_excl| ipc_creat |0666;int shm_id = shmget (Key,_SHM_SIZE_,flag ); if (shm_id < 0) {printf ("Shmid error");} else{printf ("shmid success");} return shm_id;} &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;VOID*&NBSP;AT_SHM (int shm_id) {Return shmat (shm_id,NULL,0);} INT&NBSP;DELETE_SHM (char *addr) {return shmdt (addr);} Int rm_shmctl (int shm_id) {return Shmctl (shm_id,ipc_rmid,null);} shm_test.c#include  "Shm.h" Int main () {INT&NBSP;SHM_ID&NBSP;=&NBSP;GET_SHM (); if (shm_id <  0) {printf ("HHH");} Pid_t id = fork (); if (id <0) {printf ("fork error\n"); return 1;} Else if (id == 0) {char *buf =  (char *) at_shm (shm_id);p rintf ("Child"); int  i = 0;while (i < 4095) {buf[i] =  ' A ';++i;buf[i] =  '; sleep (1) ;} buf[4095] =  ';d elete_shm (BUF);} else{int i = 0;char *buf  =  (char *) at_shm (shm_id);p rintf ("father"); while (i<4095) {printf ("%s\n", buf); ++i;sleep (1);} DELETE_SHM (BUF); Waitpid (id,null,0); Rm_shmctl (shm_id);} return 0;}

Operation Result:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7F/3A/wKioL1cXPpSRu_kZAAAhoVKHEKY607.png "title=" QQ picture 20160420162900.png "alt=" Wkiol1cxppsru_kzaaahovkheky607.png "/>


Summarize:

In fact, shared memory is the fastest way to communicate between IPC processes, because he is directly on the physical address of the operation, and for his resource control, we need to cooperate with the semaphore to operate, to prevent the generation of deadlocks.

This article is from the "egg-left" blog, please be sure to keep this source http://memory73.blog.51cto.com/10530560/1765844

Linux interprocess communication: Shared memory

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.