#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ipc.h> #include <sys/shm.h> #include <unistd.h>

struct BufferPool { int Index[10]; char Buffer[10][100]; };

int main() { int running = 1; void shm = NULL; struct BufferPool shared; char buffer[100]; int shmid; shmid = shmget((key_t)1234, sizeof(struct BufferPool), 0666|IPC_CREAT); if(shmid == -1) { exit(EXIT_FAILURE); } shm = shmat(shmid, (void)0, 0); if(shm == (void)-1) { exit(EXIT_FAILURE); } printf('Memory attached at %X\n', (int)shm); shared = (struct BufferPool*)shm; while(running) { int index = 0; if(shared->Index[index] == 1) { sleep(1); index++; } else { printf('Enter some text: '); fgets(buffer, 100, stdin); strncpy(shared->Buffer[index], buffer, 100); shared->Index[index] = 1; if(strncmp(buffer, 'end', 3) == 0) { running = 0; } } } if(shmdt(shm) == -1) {exit(EXIT_FAILURE);} if(shmctl(shmid, IPC_RMID, 0) == -1) { exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }

C语言共享内存实现进程间通信示例

原文地址: https://www.cveoy.top/t/topic/gwy1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录