Shared memory functions include the following:
(1) int shmget (key_t key, int size, int shmflg) To open up or use a shared memory.
(2) void * shmat (INT shmid, const void * shmaddr, int shmflg) connects the shared memory pointed to by the shmid parameter to the current process.
When using a shared memory, you must first use shmat to establish a connection.
(3) int shmdt (const void * shmaddr), disconnects the shared memory previously connected with shmat from the current process. The shmaddr parameter is the address of the shared memory returned by shmat.
After using the shared memory, use shmdt to cancel the connection.
(4) int shmctl (INT shmid, int cmd, struct shmid_ds * BUF) Controls Memory operations. When CMD is ipc_rmid, delete the shared memory referred to by shmid.
The header files of these functions are <sys/IPC. h> and <sys/SHM. h>. For detailed parameters, search for them online.
The following example shows how to use the shared memory to implement inter-process communication: process a opens up a new shared memory, process B modifies the shared memory, and process C prints out the shared memory content, process D deletes the shared memory.
The command format for running the BCD process is: the command shared memory ID, such as./output 123432.
Process a code is as follows:
int main(){int shmid;shmid = shmget(IPC_PRIVATE, SIZE, IPC_CREAT | 0600);if (shmid < 0){perror("shmget error");exit(1);}printf("create shared memory OK. shmid=%d/n", shmid);return 0;}
The process B code is as follows:
int main(int argc, char *argv[]){int shmid;char *shmaddr;if (argc != 2){perror("argc error/n");exit(1);}shmid = atoi(argv[1]);shmaddr = (char *)shmat(shmid, NULL, 0);if ((int )shmaddr == -1){perror("shmat error./n");exit(1);}strcpy(shmaddr, "hello, world!");shmdt(shmaddr);return 0;}
The process C code is as follows:
int main(int argc, char *argv[]){int shmid;char *shmaddr;if (argc != 2){printf("argc error/n");exit(1);}shmid = atoi(argv[1]);shmaddr = (char *)shmat(shmid, NULL, 0);if ((int )shmaddr == -1){perror("shmat error./n");exit(1);}printf("%s/n", shmaddr);shmdt(shmaddr);return 0;}
The process D code is as follows:
int main(int argc, char *argv[]){int shmid;if (argc != 2){perror("argc error/n");exit(1);}shmid = atoi(argv[1]);shmctl(shmid, IPC_RMID, NULL);return 0;}