It's all right. For examples that want to learn to use shared memory communication between processes, the efficiency of shared memory is higher than that of Message Queuing and semaphores. Why is it?
(1) Shared memory is run in user space and is controlled by the application.
(2) Both the message queue and the semaphore are the user space that copies the data from one process user space to the kernel space and then the kernel control to another process.
#include <unistd.h>#include<stdio.h>#include<string.h>#include<sys/mman.h>#include<sys/ipc.h>#include<sys/shm.h>#include<sys/stat.h>#include<sys/types.h>#include<sys/wait.h>#defineKey 0x1234#defineSize 512#definePERM s_irusr| S_iwusrintMainvoid){ intShmid=shmget (key,size,ipc_creat|PERM); Char*shm=shmat (Shmid,null,0); if(shmid==-1) {perror ("Shmget"); return-1; } if(Fork () >0){ intParent_id=Getpid (); fprintf (stdout,"----Parent pid=%d------\ n", parent_id); intstatus; while(1){ Char*p_shm=shmat (Shmid,null,0); if(STRNCMP (P_SHM,"End",3)==0) {fprintf (stdout,"***recyle Child =%d*****\n", Wait (&status)); Break; } Else{memset (P_SHM,' /', size); } printf ("Parent%d send:", parent_id); Fgets (P_shm,size,stdin); Sleep (1); } } Else { while(1){ Char*c_shm=shmat (Shmid,null,0); if(strlen (SHM) >0) {printf ("Child %d recv:%s", Getpid (), C_SHM); } if(strlen (SHM) >0&&STRNCMP (SHM,"End",3)==0) {memcpy (SHM,"End",3); Break; } Sleep (1); } } if(SHMDT (SHM) ==-1) {perror ("SHMDT"); return-1; } if(Shmctl (Shmid,ipc_rmid,null) ==-1) {perror ("Shmctl"); return-1; }}
Operation Result:
----Parent Pid=3477------Parent3477Send:hellochild3478recv:helloparent3477Send123456 Child3478Recv123456Parent3477Send Thisa testchild3478Recv Thisa testparent3477Send:endchild3478Recv:endRecyle Child =3478*****
Linux interprocess communication, using shared memory mode