linux shm 进程之间内存共享

进程之间内存共享
实例代码如下:
服务器端:

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/ipc.h>
  6. #include <sys/shm.h>

  7. #define SHM_SIZE 26

  8. int main(int argc,char* argv[])
  9. {
  10.     char* pMem = NULL;
  11.     int shmid = 0;
  12.     int i = 0;
  13.     int retcode = 0;
  14.     key_t key=ftok("/home/root",2);

  15.     shmid = shmget(key, SHM_SIZE, IPC_CREAT|0600);
  16.     if(shmid == -1)
  17.     {
  18.         perror("shmget");
  19.         exit(-1);
  20.     }

  21.     pMem = (char*)shmat(shmid, NULL, 0);
  22.     if(pMem == (char*)-1)
  23.     {
  24.         perror("shmat");
  25.         exit(-1);
  26.     }
  27.     printf("SharedMemory:%p\n",pMem);
  28.     for(i=0;i<SHM_SIZE;i++)
  29.     {
  30.         pMem[i]='a'+i;
  31.     }

  32.     while(pMem[0]!='*')
  33.         sleep(1);

  34.     retcode = shmdt(pMem);
  35.     if(retcode == -1)
  36.     {
  37.         perror("shmdt");
  38.         exit(-1);
  39.     }
  40.     retcode = shmctl(shmid, IPC_RMID, NULL);
  41.     if(retcode == -1)
  42.     {
  43.         perror("shmctl");
  44.         exit(-1);
  45.     }

  46.     return 0;
  47. }

//
客户端:

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/ipc.h>
  6. #include <sys/shm.h>

  7. #define SHM_SIZE 26

  8. int main(int argc, char* argv[])
  9. {
  10.     int i = 0;
  11.     char* pMem = NULL;
  12.     key_t key = ftok("/home/root", 2);
  13.     int shmid = shmget(key, SHM_SIZE, 0600);
  14.     if(shmid == -1)
  15.     {
  16.         perror("shmget");
  17.         exit(-1);
  18.     }
  19.     pMem = (char*)shmat(shmid,NULL,0);
  20.     if(pMem == (char*)-1)
  21.     {
  22.         perror("shmat");
  23.         exit(-1);
  24.     }
  25.     printf("Client:SharedMemoryat%p\n", pMem);
  26.     for(i=0; i<SHM_SIZE; i++)
  27.     {
  28.         putchar(pMem[i]);
  29.     }
  30.     putchar('\n');
  31.     pMem[0]='*';
  32.     shmdt(pMem);
  33.    
  34.     return 0;
  35. }

转载自: http://hi.baidu.com/jiangxun_lin/blog/item/9ae6703244df8abf5fdf0ef9.html
<script type=text/javascript charset=utf-8 src="http://static.bshare.cn/b/buttonLite.js#style=-1&uuid=&pophcol=3&lang=zh"></script> <script type=text/javascript charset=utf-8 src="http://static.bshare.cn/b/bshareC0.js"></script>
阅读(263) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~
评论热议
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值