Inter-Process Communication --System V IPC shared memory

  What is the System V IPC?

  It is a Unix System V operating system, the system introduces three high-level communication mechanism between the process: message queues, shared memory, semaphore. System V IPC IPC is a three collectively:

  System V semaphore queue System V message System V shared memory

  Message queues, semaphores, shared memory is also referred to as IPC objects. You can view the current IPC objects through ipcs, IPC objects can be deleted by ipcrm.

. 1    the ipcs - Q: Displays the message queue.
2    the ipcs - S: Show only semaphores.
. 3    the ipcs - m: display only the shared memory.
4    ipcs -help: Other parameters

  IPC objects present in the kernel rather than the file system, the controlled release by the user, unlike the release conduit controlled by the kernel

       IPC objects to reference and access to all IPC objects in the kernel space by its unique identifier of the tag ID, a unique identifier in the user space called key

  IPC function to create objects

  Unix system, everything is a file, the operation is in many IPC mechanism for the file descriptor, but is for the system V IPC target operation ID, and ID (identifier) ​​is generated by the key (key).

  ftok() ---> key ------>  ID

  Then look at the ftok function:

  ftok () function

. 1 #include <SYS / types.h>
 2 #include <SYS / ipc.h>
 . 3  
. 4 key_t ftok ( const  char * pathname, int PROJ_ID);
 . 5  // pathname for the file path name must be present and accessible, often the current path name "."
 . 6  // PROJ_ID sub ID, used for generating the digital key, and 1-255 
. 7 

  System V IPC See: https://blog.csdn.net/qq_38211852/article/details/80475818

 

Shared memory

  Shared memory allows different processes to access the same logical memory, memory read and write directly, without any need to copy data, for communication message queues, pipes, etc., required data is copied four times in kernel space, but requires only memory happy copies twice, once the input file to the shared memory area, the shared memory area from another to the output file. .

  Shared memory in kernel space is created that can be mapped to user space access , use and flexible. (I.e. associated mapping: a kernel memory as an address, i.e. access kernel space by mapping to a user space, after the user access to a space as a.)

  Shared memory does not provide a synchronization mechanism, it is necessary to use other mechanisms to achieve different processes access to shared memory.

    Shared memory using the steps

1 Create / open a shared memory
 2  mapped shared memory that is mapped to the specified shared memory address space of a process used to access
 3  to read and write shared memory
 4  revocation of shared memory mapping
 5 delete shared memory object

  1, shared memory created -shmget

. 1 #include <SYS / ipc.h>
 2 #include <SYS / shm.h>
 . 3  
. 4  int shmget (key_t Key, size_t size, int shmflg);
 . 5  
. 6  // returns successfully shared memory ID, failed to return the EOF
 . 7  // parameters:
 . 8  // key --- fotk be generated as a shared memory segment command, the function returns an identifier associated with the key
 . 9  // size in bytes specified --- required shared memory
 10  // shmflg --- permission flags, such as: IPC_CREAT | 0666

  Example 1: Creating a private shared memory, size of 512 bytes, 0666 permissions

1 int shmid;
2 
3 if((shmid = shmget(IPC_PRIVATE, 512, 0666)) < 0)
4 {
5       perror("shmget");
6       exit(-1);            
7 }

  Example 2: Create / Open and a KEY associated shared memory, size of 1024 bytes, 0666 permissions

 1 key_t key;
 2 int shmid;
 3 
 4 if((key = ftok(".", 'm')) == -1)
 5 {
 6      perror("ftok");
 7      exit(-1);
 8 }
 9 if((shmid = shmget(key, 1024, IPC_CREAT|0666)) < 0)
10 {
11       perror("shmget");
12       exit(-1);            
13 }

 

  2, shared memory mapping -shmat

. 1 #include <SYS / ipc.h>
 2 #include <SYS / shm.h>
 . 3  
. 4  void * the shmat ( int the shmid, const  void * by shmaddr, int shmflg);
 . 5  
. 6  // After the successful return address mapping failure return (void *) -. 1
 . 7  // parameters:
 . 8  // the shmid --- shared memory ID to be mapped
 . 9  // by shmaddr --- mapped address, NULL represented by the automatic mapping system
 10  // shmflg --- flag, table 0 can be read; SHM_RDONLY read-only table

  shmat - share memory attach, the application layer can not directly access the kernel memory through the system call, the kernel shared memory mapped to user space.

  3, write shared memory

  Access the shared memory through pointers, pointer type depending on the type of data stored in the shared memory

  Example: keyboard input character string is stored in shared memory

 1 char *addr;
 2 int shmid;
 3 ...
 4 if((addr = (char *)shmat(shmid, NULL, 0)) == (char *)-1)
 5 {
 6       perror("shmat");
 7       exit(-1);  
 8 }
 9 fgets(addr, N, stdin);
10 ...

 

  4, revocation of shared memory mapping -shmdt

  The shared memory separate from the current process, the separation is not deleted, just so that the shared memory for the current process is no longer available.

. 1 #include <SYS / ipc.h>
 2 #include <SYS / shm.h>
 . 3  
. 4  int shmdt ( const  void * by shmaddr);
 . 5  
. 6  // return 0 on success, failure EOF
 7  // parameters:
 8  // shmaddr --- to shmat function returns the address pointer
 9  // shall revoke the map when not in use shared memory
 10  // automatically withdrawn at the end of the process

 

  5, the shared memory control -shmctl

  For control of the shared memory

. 1 #include <SYS / ipc.h>
 2 #incude <SYS / shm.h>
 . 3  
. 4  int the shmctl ( int the shmid, int cmd, struct the shmid_ds * buf);
 . 5  
. 6  // Returns 0 on success, failure to return the EOF
 . 7  / / parameters
 . 8  // the shmid --- id to operate the shared memory
 9  // operations to be performed cmd ---  
 10  @        IPC_STAT: shmid_ds coverage value with the current value of the associated shared memory.
11  //        IPC_SET: if the process has sufficient rights, put the value of the shared memory is currently associated shmid_ds structure set to the value given in
 12  //        IPC_REID: delete the shared memory segment

 

Precautions:

  Each shared memory size is limited, by the following commands can be viewed

  ipcs -l

  cat /proc/sys/kernel/shmmax

  Shared memory deletion of the point in time

  shmctl (shmid, IPC_RMID, NULL); Add Remove tag

  When 0 when nattach become really deleted.

test program

Read and write to shared memory by shm_write and shm_read these two processes

shm_wirte.c

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <sys/ipc.h>
 5 #include <sys/shm.h>
 6 
 7 int main()
 8 {
 9     key_t key;
10     int shmid;
11     char *addr; //定义映射后的地址
12     key = ftok(".",23);
13     if(key == -1)
14     {
15         perror("ftok " );
 16          return - . 1 ;
 . 17      }
 18 is      the shmid = shmget (Key, 1024 , the IPC_CREAT | 0666 ); // Create a shared memory 
. 19      IF (the shmid == - . 1 )
 20 is      {
 21 is          perror ( " shmget " );
 22 is          return - . 1 ;
 23 is      }
 24      
25      addr = the shmat (the shmid, NULL, 0 ); // mapping shared memory 
26 is  
27      strcpy (addr," The this IS Share Memory " ); // read the shared memory 
28  
29      shmdt (addr); // undo the shared memory mapping 
30  
31 is  
32 }

shm_read.c

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <sys/ipc.h>
 5 #include <sys/shm.h>
 6 
 7 int main()
 8 {
 9     key_t key;
10     int shmid;
11     char *addr; //定义映射后的地址
12     key = ftok(".",23);
13     if(key == -1)
14     {
15         perror("ftok " );
 16          return - . 1 ;
 . 17      }
 18 is      the shmid = shmget (Key, 1024 , the IPC_CREAT | 0666 ); // Create a shared memory 
. 19      IF (the shmid == - . 1 )
 20 is      {
 21 is          perror ( " shmget " );
 22 is          return - . 1 ;
 23 is      }
 24      
25      addr = the shmat (the shmid, NULL, 0 ); // mapping shared memory
 26 is  
27  @    strcpy (addr, "the this IS Share Memory"); // read the shared memory 
28      the printf ( " GET Share Memory% S = \ n- " , addr);
 29      shmdt (addr); // undo the shared memory mapping 
30  
31 is  
32 }

result:

Detailed shared memory excellent blog: https://www.cnblogs.com/linuxbug/p/4882776.html

Guess you like

Origin www.cnblogs.com/y4247464/p/12109332.html