共享内存
共享内存是IPC机制中的一种,它允许两个相关的进程访问同一段内存,这是传递数据的一种有效的方式。
A.c
#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #include <string.h> #define SIZE 2048 typedef struct sharemem{ int flag; //共享标志 char data[SIZE]; //共享数据 }ShareMem; void main(){ //创建共享内存 int key; int shmid; key = ftok("./", 0); shmid = shmget(key, sizeof(ShareMem), IPC_CREAT); //映射共享内存 ShareMem *shareMem; shareMem = (ShareMem *)shmat(shmid, NULL, 0); //设置共享内存 shareMem->flag = 0; while(1){ //判断共享标志 while(shareMem->flag != 0); //获取用户输入 char buffer[SIZE]; fgets(buffer, SIZE, stdin); //写入共享内存 strncpy(shareMem->data, buffer, SIZE); shareMem->flag = 1; //判断是否退出 if(strncmp(buffer, "quit", 4) == 0){ break; } } //脱离共享内存 shmdt((const void *)shareMem); }
B.c
#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #include <string.h> #define SIZE 2048 typedef struct sharemem{ int flag; //共享标志 char data[SIZE]; //共享数据 }ShareMem; void main(){ //打开共享内存 int key; int shmid; key = ftok("./", 0); shmid = shmget(key, sizeof(ShareMem), IPC_CREAT); //映射共享内存 ShareMem *shareMem; shareMem = (ShareMem *)shmat(shmid, NULL, 0); //设置共享内存 shareMem->flag = 1; while(1){ //判断共享标志 while(shareMem->flag != 1); //读取共享内存 char buffer[SIZE]; strncpy(buffer, shareMem->data, SIZE); shareMem->flag = 0; //显示共享内存 printf("%s", buffer); //判断是否退出 if(strncmp(buffer, "quit", 4) == 0){ break; } } //脱离共享内存 shmdt((const void *)shareMem); //删除共享内存 shmctl(shmid, IPC_RMID, NULL); }
时间: 2024-11-01 09:40:51