memory.c

沐 雨 2019-04-16 04:11:46
#include<unistd.h> #include<sys/ipc.h> #include<sys/shm.h> #include<errno.h> #define KEY 1234 //键 #define SIZE 1024 //欲建立的共享内存的大小 int main(){ int shmid; char *shmaddr; struct shmid_ds buf; shmid=shmget(KEY,SIZE,IPC_CREAT|0600);//建立共享内存 if(shmid==-1){ printf("create share memory failed: %s",strerror(errno)); return 0; } if(fork()==0){ shmaddr=(char *)shmat(shmid,NULL,0);//系统自动选择一个地址连接 if(shmaddr==(void *)-1){ printf("connect to the share memory failed: %s",strerror(errno)); return 0; } strcpy(shmaddr,"hello,this is child process!\n"); shmdt(shmaddr); //断开与共享内存的连接 return 0; } else { sleep(3); //等待子进程执行完毕 shmctl(shmid,IPC_STAT,&buf); //取得共享内存的相关信息 printf(" size of the share memory:"); printf("shm_segsz=%d bytes \n",buf.shm_segsz); printf("process id of the creator:"); printf("shm_cpid=%d\n",buf.shm_cpid); printf("process id of the last operator:"); printf("shm_lpid=%d\n",buf.shm_lpid); shmaddr=(char *)shmat(shmid,NULL,0);//系统自动选择一个地址连接 if(shmaddr==(void *)-1){ printf("connect to the share memory failed: %s",strerror(errno)); return 0; } printf("print the content of the share memory:"); printf("%s\n",shmaddr); shmdt(shmaddr); //断开与共享内存的连接 shmctl(shmid,IPC_RMID,NULL); //当不再有任何其他进程使用该共享内存时系统将自动销毁它 } }
...全文
20 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

4,436

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 内核源代码研究区
社区管理员
  • 内核源代码研究区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧