This series of articles written by muge0913, reproduced please note the Source: http://blog.csdn.net/muge0913/article/details/7342653
Shared memory is the most underlying communication mechanism in Lunix and the fastest communication mechanism. Shared Memory enables communication between processes by sharing two or more processes in the same memory area. A shared block is usually created by a process.
Memory area, and multiple processes can access it. The data to be transmitted from one process is stored in the shared memory, and the other or multiple processes read data directly from the shared memory. Therefore, this communication method is the most efficient method for inter-process communication. But the actual problem is that when two or more processes use shared memory for communication, the solution to the synchronization problem is particularly important, otherwise, confusion may occur because different processes read and write data in a shared memory at the same time. In general, processes are synchronized by using semaphores.
The preceding two programs are examples of inter-process communication. The two programs run in different processes and use shared memory for communication. B reads data from the keyboard and stores it in the shared memory. A reads data from the shared memory and displays the data on the screen. Because the two processes are not synchronized, the displayed content will be disordered. The handling of this problem will be completed after further learning about the synchronization operations.
Instance B is responsible for writing data to the shared memory, and program A is responsible for reading the shared data from the memory, and no synchronization operation is added between them.
B .C
#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>#define BUF_SIZE 1024#define MYKEY 25int main(){ int shmid; char *shmptr; if((shmid = shmget(MYKEY,BUF_SIZE,IPC_CREAT)) ==-1) { printf("shmget error \n"); exit(1); } if((shmptr =shmat(shmid,0,0))==(void *)-1) { printf("shmat error!\n"); exit(1); } while(1) { printf("input:"); scanf("%s",shmptr); } exit(0);}
A. c
#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#define BUF_SIZE 1024#define MYKEY 25int main(){ int shmid; char * shmptr; if((shmid = shmget(MYKEY,BUF_SIZE,IPC_CREAT)) ==-1) { printf("shmget error!\n"); exit(1); } if((shmptr = shmat(shmid,0,0)) == (void *)-1) { printf("shmat error!\n"); exit(1); } while(1) { printf("string :%s\n",shmptr); sleep(3); } exit(0);}