IPC 共享内存


共享内存解释:




linux中进程对任何非进程地址空间的访问都是违法的,所以进程1和进程2是不能直接访问共享内存区域的,共享内存在进程1和进程2的地址空间中都会映射一段同样大小的内存区域,所有挂载在该共享内存上的进程都会开辟同样大小的内存,所有对进程内存的操作都会被同步到共享内存,以此实现进程间的通信。


创建共享内存的方法:

  1. #include<stdio.h>
  2. #include<sys/ipc.h>
  3. #include<sys/shm.h>
  4. #define BUF_SIZE 1024
  5. int main()
  6. {
  7. int id = shmget(IPC_PRIVATE,BUF_SIZE,0666);
  8. if(id==-1)
  9. {
  10. perror("create shared memory fail");
  11. }
  12. system("ipcs -m");
  13. return 0;
  14. }



新创建的共享内存上的挂载进程数为0。

在某个共享内存上挂载进程:



  1. #include<stdio.h>
  2. #include<sys/types.h>
  3. #include<sys/shm.h>
  4. #include<stdlib.h>
  5. int main(int args,char* argc[])
  6. {
  7. if(args<2)
  8. {
  9. puts("input the shmid!");
  10. exit(-1);
  11. }
  12. int shmid = atoi(argc[1]);
  13. char* addr = shmat(shmid,0,0);
  14. if(addr!=(void*)-1)
  15. {
  16. perror("shmat error");
  17. }
  18. system("ipcs");
  19. while(1);
  20. return 0;
  21. }

shmat的第一个参数是共享内存的id,第二个参数为0表示进程导入点的内存地址由系统决定,也可以指定导入点,不过不建议这样做,第三个参数为0表示这段内存地址可以读写,返回值为进程共享内存导入点的地址,如果失败,返回(void*)-1

开启三个终端,运行:



发现nattch变为3,表示目前共有3个进程共享这片内存区域。

从某共享内存上卸载进程:



参数为shmat的返回值。

使用共享内存进行进城之间的通信:

  1. #include<stdio.h>
  2. #include<sys/types.h>
  3. #include<sys/shm.h>
  4. #include<stdlib.h>
  5. int main(int args,char* argc[])
  6. {
  7. if(args<3)
  8. {
  9. puts("error!");
  10. exit(-1);
  11. }
  12. int shmid = atoi(argc[1]);
  13. int oper = atoi(argc[2]);
  14. char* addr = shmat(shmid,0,0);
  15. if(addr==(void*)-1)
  16. {
  17. perror("shmat error");
  18. exit(-1);
  19. }
  20. if(oper==1) // write shared memory
  21. {
  22. scanf("%s",addr);
  23. }
  24. else if(oper==2) // read shared memory
  25. {
  26. printf("%s\n",addr);
  27. }
  28. return 0;
  29. }













posted @ 2015-06-09 22:02  外禅内定,程序人生  阅读(418)  评论(0编辑  收藏  举报