1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> struct shared_msg { int update; char text[BUFSIZ]; }; void main() { printf("程序开始\n"); key_t key; int shmid; struct shared_msg *msg; char buf[BUFSIZ]; key = (key_t)1234; shmid = shmget(key,sizeof(struct shared_msg),IPC_CREAT|0666); if(shmid < 0){ fprintf(stderr, "创建共享内存失败\n"); exit(EXIT_FAILURE); } msg = (struct shared_msg*)shmat(shmid,NULL,0); if( msg < (struct shared_msg*)0 ){ fprintf(stderr, "共享内存段映射到进程失败n"); exit(EXIT_FAILURE); } printf("共享内存地址 %X\n", (int)msg); while(1){ while(msg->update == 1){ sprintf(buf,"%s",msg->text); printf("读取数据:%s",buf); msg->update = 0; } if(strncmp(buf,"EOF",3) == 0){ break; } } if(shmdt(msg) < 0){ fprintf(stderr, "将共享内存和当前进程分离失败\n"); exit(EXIT_FAILURE); } if(shmctl(shmid, IPC_RMID, 0) == -1) { fprintf(stderr, "删除共享内存失败\n"); exit(EXIT_FAILURE); } printf("程序结束\n"); exit(EXIT_SUCCESS); }
|