Shared storage for inter-process communication in LINUX

Source: Internet
Author: User

Shared storage for inter-process communication in LINUX
LINUX inter-process communication 1. Anonymous and named pipelines 2. Message Queue 3. shared storage

Shared storage Overview: shared storage allows two or more processes to share a given storage zone. The shared memory zone is the fastest form of IPC. Once such memory is mapped to the address space of the process sharing it, data transmission between these processes no longer involves the kernel, that is to say, the process no longer needs to switch to the kernel state to transmit data. Therefore, shared storage is more efficient than Message Queue switching between user and kernel. Related commands:

Ipcs-m: view the shared memory segments in the current kernel;
Ipcrm-m + shmid: Delete the shared memory segments of the corresponding shmid.

Shared Memory:

That is to say, the process obtains the shmid of the same shared storage area at the same time, uses shmat to connect the corresponding shared storage space to its own process address space, and then uses shmdt to disconnect after the operation is complete. You do not need to switch the status multiple times during the overall use process. Shared Memory Data Structure:

Function introduction:1. shmget: Get the shared storage identifier
# Include
 
  
# Include
  
   
Int shmget (key_t key, size_t size, int shmflg); // return value: the identifier of the shared memory is returned successfully. If it fails,-1 is returned.
  
 
Parameter description: ① key: Same as the message queue, both are generated by the ftok function; ② size: shared memory size (Unit/byte ); generally, it is rounded up to an integer multiple of the system page length. ③ shmflg: The usage is the same as the mode flag used for file creation. Refer to the introduction in message queue. Ii. shmctl: controls the shared memory
# Include
 
  
# Include
  
   
Int shmctl (int shmid, int cmd, struct shmid_ds * buf); // success returns 0, Failure Returns-1
  
 
Parameter description: ① shmid: the shared memory ID to be operated on; ② cmd: the operations to be performed (IPC_STAT, IPC_SET, IPC_RMID) ③ buf: A struct pointer pointing to the shmid_ds struct type. When the parameters are IPC_STAT and IPC_SET, you must specify a struct to specify the modified value. 3. shmat: connect the shared memory segment to the process address space
# Include
 
  
# Include
  
   
Void * shmat (int shmid, const void * shmaddr, int shmflg); // return value: a pointer to the first byte of the shared memory is returned, and-1 is returned if no value is returned.
  
 
Parameter Introduction: ① shmid: the shared memory identifier generated by ftok; ② shmaddr: Specifies the connection address; ③ shmflg: SHM_RND and SHM_RDONLY are recommended.
Shmaddr is set to NULL. The kernel automatically selects an address shmaddr not to be NULL, and shmflg does not have the SHM_RND mark. shmaddr is used as the connection address. shmaddr is not NULL, and shmflg is set to the SHM_RND mark, the connection address is automatically adjusted down to an integer multiple of SHMLBA, shmflg = SHM_RDONLY, indicating that the connection operation is used to read-only shared memory.
Note: For more details, see man or advanced programming in unix. 4. shmdt: disconnects the shared memory segment from the current process
# Include
 
  
# Include
  
   
Void * shmat (int shmid, const void * shmaddr, int shmflg); int shmdt (const void * shmaddr); // return value: 0 for success,-1 for failure
  
 
Parameter description: shmaddr: pointer returned by shmat. Note: 1. Shared memory does not have a synchronization mutex mechanism !! 2. Shared Memory segments are used with the kernel, so it is best to disconnect from the shared memory when the process is no longer used before it ends. Example: in a shared memory storage area, the client writes data to it, and the server reads and prints the data to the screen.
/**********comm.h*************/#pragma once#include 
 
  #include 
  
   #include 
   
    #include 
    
     #define PATHNAME "."#define PROJ_ID 0x66int createShm(int size);int destroyShm(int shmid);int getShm(int size);/**********comm.c**********/#include "comm.h"int commShm(int size, int flags){    key_t key = ftok(PATHNAME, PROJ_ID);    if(key < 0){        perror("ftok");        return -1;    }    int shmid = shmget(key, size, flags);    if(shmid < 0){        perror("shmget");        return -2;    }    return shmid;}int destroyShm(int shmid){    if(shmctl(shmid, IPC_RMID, NULL) < 0){        perror("shmctl");        return -1;    }    return 0;}int creatShm(int size){    return commShm(size, IPC_CREAT | IPC_EXCL | 0666);}int getShm(int size){    return commShm(size, IPC_CREAT);}/**********client.c********/#include "comm.h"int main(){    int shmid = getShm(4094);    char* addr = shmat(shmid, NULL, 0);    sleep(1);    int i = 0;    while(i < 5){        addr[i] = 'A' +i;        i++;        addr[i] = 0;        sleep(1);    }    shmdt(addr);    sleep(2);    return 0;}/*********server.c*******/#include "comm.h"int main(){    int shmid = creatShm(4096);    char* addr = (char*)shmat(shmid, NULL, 0);    sleep(5);    int i = 0;    while(i < 10){        i++;        printf("client> %s\n",addr);        sleep(1);    }    shmdt(addr);    sleep(2);    destroyShm(shmid);    return 0;}/*******Makefile********/.PHONY : allall : server clientserver : server.c comm.c    gcc $^ -o $@client : client.c comm.c    gcc $^ -o $@.PHONY : cleanclean:    rm server client
    
   
  
 
Running result: Open the server and then the client. After sleep, the client writes data to the shared memory, and the server keeps reading data. However, when the client stops writing data, the data in the shared memory area is the last data written, so it is output five more times.

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.