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

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

int main(){ int running = 1; void shm = NULL; struct BufferPool shared; char buffer[100]; int shmid, index; 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){ 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语言共享内存示例:使用IPC_CREAT创建共享内存段

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

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