[Linux] Shared memory __linux

Source: Internet
Author: User
shared Memory is one of the fastest and fastest forms of IPC that UNIX provides for interprocess communication. Why is the fastest, because the data does not need to be replicated between the client process and the server process, so it is the fastest IPC. This is a common block of memory that is shared by multiple processes in a virtual store. two different processes A, B shared memory means that the same physical memory is mapped to process A, B's respective process address space. Process A can instantly see Process b update of the data in shared memory, and vice versa. If the server process is putting data into a shared store, the client process should not fetch the data until it has done so. Typically the semaphore is used to synchronize shared storage access. since shared memory is communicated by mapping to the same physical memory, it is certain that the functions mapped to memory and the functions that are unmapped are required, mainly in the following
#define SHMAT       21//space map: Connect the Open memory area to the user's process space  
#define SHMDT       22//Unlock: Detach the shared memory from the current process  
#define Shmget      23//Create controls that open an area  
of memory #define SHMCTL      24//Memory areas: initialization and deletion of memory areas.
Note: The shared memory communication itself does not provide a synchronization mechanism, which can cause damage to the contents of the memory space if it is mapped and written by multiple processes at the same time. Therefore, in the actual application process, we need to use other mechanisms to synchronize access to shared memory. such as signal volume. The kernel maintains a structure for each shared storage segment that contains the following members for at least each shared storage segment:
struct Shmid_ds 
{
    struct ipc_perm shm_perm;//IPC structure size_t
    shm_segsz;  The requested size
    pid_t shm_lpid;   0
    pid_t shm_cpid;   Creator PID
    shmatt_t shm_nattch//Current mount number
    time_t shm_atime;  0
    time_t shm_dtime;//0
    time_t shm_ctime;  Set to current time
};
1. The first function called is shmget:
#include <sys/shm.h>
int shmget (key_t key,size_t size,int flag);
Key is the unique identifier that creates the shared memory ID, which is the length of the shared storage segment, in bytes, and is typically rounded up to an integer multiple of the length of the system page. If it is not an entire page, the last remaining part is not available. Flag represents the appropriate permission bit.
2.shmctl function performs multiple operations on shared memory segments
#include <sys/shm.h>
int shmctl (int shmid,int cmd,struct shmid_ds *buf);
Ipc_rmid: Deletes the shared storage segment from the system.
3. Once a shared storage segment is created, the process can call Shmat to connect it to its address space.
void *shmat (int shmid,const void* addr,int flag);
Returns if successful, returns a pointer to a shared storage segment, error return-1
//If successful, the kernel will add 1 to the Shm_nattch counter value in the SHMID_DS structure associated with the shared storage segment, and when the operation on the shared storage segment has ended, The call Shmat is detached from the segment. There is no related data structure removed from the system, and the identifier and IPC data structures still exist.
int SHMDT (const void* addr);  Addr
///If the call succeeds, the Shm_nattch counter value in the SHMID_DS structure associated with the shared storage segment is reduced by 1
Specific code implementation:
Comm.h
#ifndef _comm_h_
#define _comm_h_
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define PATHNAME "."
#define PROJ_ID 0x6667

int createshm (int size);
int getshm (int size);

int destroyshm (int shmid);






#endif   //_comm_h_
//comm.c #include "comm.h" int commshm (int size,int flags) {key_t key = Ftok (pathname,proj_i
    D);
        if (Key < 0) {perror ("Ftok");
    return-1; 
    int shmid = Shmget (key,size,flags);
        if (Shmid < 0) {perror ("Shmget");
    Return-2;
return shmid; int createshm (int size) {return COMMSHM size,ipc_creat|
ipc_excl|0666); int getshm (int size) {return commshm (size,ipc_creat);} int destroyshm (int shmid) {if Shmctl (shmid,ipc_rmid,nu
        LL) < 0) {perror ("Shmctl");
    return-1;
return 0; }
Server.c
#include "comm.h"

int main ()
{
    int shmid = CREATESHM (4096);  printf ("Hello server!\n");
    Char *addr = Shmat (shmid,null,0);
    if (addr = = NULL)
    {return
        1;
    }
    int i = 0;
    char s = ' a ';
    while (1)
    {
        Addr[i] = s;
        s++;
    }
    Addr[i] = 0;
    Sleep (4);
    SHMDT (addr);
    printf ("Shm quit!\n");
    return 0;
}
Client.c
#include "comm.h"

int main ()
{
    int shmid = GETSHM (4096);
    printf ("Hello client!\n");
    Char *addr = Shmat (shmid,null,0);
    if (addr = NULL) return
        2;
    printf ("%s", addr);

    Sleep (a);
    SHMDT (addr);    
    printf ("Shm quit!\n");
    return 0;
}
Run Result:

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.