共享主存实现进程间通信

写程序

 

 
 
  1. #include"sys/ipc.h"  
  2. #include"sys/shm.h"  
  3. #include"sys/types.h"  
  4. #include"unistd.h"  
  5. #include"stdio.h"  
  6. #include"string.h"  
  7. typedef struct{  
  8.     char name[4];  
  9.     int age;  
  10. }people;  
  11.  
  12. main(int argc,char** argv)  
  13. {  
  14.     int shm_id,i;  
  15.     key_t key;  
  16.     char temp;  
  17.     people *p_map;  
  18.     char* name="..";  
  19.     key=ftok(name,0);  
  20.     if(key==-1)  
  21.         perror("ftok error!");  
  22.     shm_id=shmget(key,4096,IPC_CREAT|0666);  
  23.     if(shm_id==-1)  
  24.     {  
  25.         perror("shmget error!");  
  26.         return;  
  27.     }  
  28.     p_map=(people*)shmat(shm_id,NULL,0);  
  29.     temp='a';  
  30.     for(i=0;i<10;i++)  
  31.     {  
  32.         temp++;  
  33.         memcpy((*(p_map+i)).name,&temp,1);  
  34.         (*(p_map+i)).age=20+i;  
  35.     }  
  36.     if(shmdt(p_map)==-1)  
  37.         perror("detach error!");  
  38. }  

读程序

 

 
 
  1. #include"sys/ipc.h"  
  2. #include"sys/shm.h"  
  3. #include"sys/types.h"  
  4. #include"unistd.h"  
  5. #include"stdio.h"  
  6. typedef struct{  
  7.     char name[4];  
  8.     int age;  
  9. }people;  
  10.  
  11. main(int argc,char** argv)  
  12. {  
  13.     int shm_id,i;  
  14.     key_t key;  
  15.     //char temp;  
  16.     people *p_map;  
  17.     char* name="..";  
  18.     key=ftok(name,0);  
  19.     if(key==-1)  
  20.         perror("ftok error!");  
  21.     shm_id=shmget(key,4096,IPC_CREAT|0666);  
  22.     if(shm_id==-1)  
  23.     {  
  24.         perror("shmget error!");  
  25.         return;  
  26.     }  
  27.     p_map=(people*)shmat(shm_id,NULL,0);  
  28.     //temp='a';  
  29.     for(i=0;i<10;i++)  
  30.     {  
  31.         printf("name:%s\n",(*(p_map+i)).name);  
  32.         printf("age %d\n",(*(p_map+i)).age);  
  33.     }  
  34.     if(shmdt(p_map)==-1)  
  35.         perror("detach error!");  
  36. }  

 

本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/732489

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值