共享主存实现进程间通信

写程序

 
  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. typedefstruct{
  8. charname[4];
  9. intage;
  10. }people;
  11. main(intargc,char**argv)
  12. {
  13. intshm_id,i;
  14. key_tkey;
  15. chartemp;
  16. people*p_map;
  17. char*name="..";
  18. key=ftok(name,0);
  19. if(key==-1)
  20. perror("ftokerror!");
  21. shm_id=shmget(key,4096,IPC_CREAT|0666);
  22. if(shm_id==-1)
  23. {
  24. perror("shmgeterror!");
  25. return;
  26. }
  27. p_map=(people*)shmat(shm_id,NULL,0);
  28. temp='a';
  29. for(i=0;i<10;i++)
  30. {
  31. temp++;
  32. memcpy((*(p_map+i)).name,&temp,1);
  33. (*(p_map+i)).age=20+i;
  34. }
  35. if(shmdt(p_map)==-1)
  36. perror("detacherror!");
  37. }

读程序

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值