One, what is shared memoryShared memory allows two unrelated processes to access the same logical memory. Shared memory is a very efficient way to share and pass data between two running processes. Memory that is shared between different processes is usually scheduled as the same piece of physical memory. Processes can connect the same piece of shared memory to their own address space, and all processes can access the addresses in the shared memory as if they were allocated by the C-language function malloc. If a process writes data to shared memory, the changes will immediately affect any other process that can access the same piece of shared memory.
Note:Shared memory does not provide a synchronization mechanism, that is, there is no automatic mechanism to prevent the second process from starting to read the shared memory until the first process ends the write operation. So we usually need to use other mechanisms to synchronize access to shared memory, such as the amount of semaphores mentioned earlier. Ii. implementation Step 1. Create shared Memory Shmget 2. Map shared memory Shmat, map the shared memory created to the process 3. de-mapping SHMDT
int shmget (key_t key, size_t size, int SHMFLG); // Key The value 0/ipc_private ipc_create when creating a piece of memory /span>// size how many bytes // flag
Returns the identifier of the shared memory
void *shmat (intconstvoidint SHMFLG); // The identifier of the de shared memory is returned when it is created/ / flag determines in what way the map is generally 0//
int shmdt (constvoid *shmaddr);
Wait usage in Linux
Once the process has called wait, it blocks itself immediately, and the wait automatically parses if a child process of the current process has exited, and if it finds such a child process that has become a zombie, wait will collect information about the child process and destroy it and return it. If no such child process is found, W AIT will always be stuck here until one appears.
#include <stdlib.h>#include<stdio.h>#include<string.h>#include<errno.h>#include<unistd.h>#include<sys/stat.h>#include<sys/types.h>#include<sys/ipc.h>#include<sys/shm.h>#definePERM s_irusr| S_iwusr/*Shared Memory*/intMainintargcChar**argv) { intShmid; Char*p_addr,*c_addr; if(argc!=2) {fprintf (stderr,"usage:%s\n\a", argv[0]); Exit (1); } /*Create shared Memory*/ if(Shmid=shmget (Ipc_private,1024x768, PERM)) ==-1) {fprintf (stderr,"Create Share Memory error:%s\n\a", Strerror (errno)); Exit (1); } /*Create Child process*/ if(Fork ())//Parent Process writes{p_addr=shmat (Shmid,0,0);//0 means the system automatically assigns you an address .memset (P_ADDR,' /',1024x768); strncpy (p_addr,argv[1],1024x768); Wait (NULL); //frees resources, does not care about termination statusExit0); } Else //Child process Read{sleep (1);//pause for 1 secondsC_addr=shmat (Shmid,0,0); printf ("Client Get%p\n", C_ADDR); Exit (0); } }
Linux Inter-process communication-shared memory