Shared Memory principle
Shmget function Syntax:
Shmat function syntax
SHMDT function syntax
Code Analysis:
/*SHMEM.C*/#include<sys/types.h>#include<sys/ipc.h>#include<sys/shm.h>#include<stdio.h>#include<stdlib.h>#include<string.h>#defineBuffer_size 2048intMain () {pid_t pid; intShmid; Char*shm_addr; CharFlag[] ="wrote"; CharBuff[buffer_size]; /*Create shared Memory*/ if(Shmid = Shmget (Ipc_private, Buffer_size,0666)) <0) {perror ("Shmget"); Exit (1); } Else{printf ("Create share-memory:%d\n", Shmid); } /*Show shared memory condition*/System ("ipcs-m"); PID=Fork (); if(PID = =-1) {perror ("Fork"); Exit (1); } Else if(PID = =0)/*Child Process Processing*/ { /*Mapping Shared Memory*/ if(shm_addr = Shmat (Shmid,0,0)) == (void*)-1) {perror ("Child:shmat"); Exit (1); } Else{printf ("Child:attach shared-memory:%p\n", SHM_ADDR); } System ("ipcs-m"); /*Verify that the parent process has written valid data to the shared memory by checking whether the header of the shared memory is a flag string wrote*/ while(strncmp (SHM_ADDR, Flag, strlen (flag))) {printf ("child:wait for Enable data...\n"); Sleep (5); } /*get valid data for shared memory and display*/strcpy (Buff, shm_addr+strlen (flag)); printf ("child:shared-memory:%s \ n", Buff); /*To disassociate a shared memory map*/ if((SHMDT (SHM_ADDR)) <0) {perror ("SHMDT"); Exit (1); } Else{printf ("Child:deattach shared-memory\n"); } System ("ipcs-m"); /*Delete Shared memory*/ if(Shmctl (Shmid, Ipc_rmid, NULL) = =-1) {perror ("child:shmctl (ipc_rmid) \ n"); Exit (1); } Else{printf ("Delete shared-memory\n"); } System ("ipcs-m"); } Else /*Parent Process Processing*/ { /*Mapping Shared Memory*/ if(shm_addr = Shmat (Shmid,0,0)) == (void*)-1) {perror ("Parent:shmat"); Exit (1); } Else{printf ("Parent:attach shared-memory:%p\n", SHM_ADDR); } Sleep (1); printf ("\ n Input some string: \ n"); Fgets (Buff, buffer_size, stdin); strncpy (shm_addr+strlen (flag), Buff, strlen (buff)); strncpy (SHM_ADDR, Flag, strlen (flag)); /*To disassociate a shared memory map*/ if((SHMDT (SHM_ADDR)) <0) {perror ("PARENT:SHMDT"); Exit (1); } Else{printf ("Parent:deattach shared-memory\n"); } System ("ipcs-m"); Waitpid (PID, NULL,0); printf ("finished\n"); } return 0;}
Shared memory of process communication