Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1552135
  • 博文数量: 239
  • 博客积分: 1760
  • 博客等级: 上尉
  • 技术积分: 1595
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-08 23:53
文章分类

全部博文(239)

文章存档

2016年(1)

2015年(28)

2014年(53)

2013年(42)

2012年(50)

2011年(65)

分类: LINUX

2012-05-03 22:57:06

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

点击(此处)折叠或打开

  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
阅读(1237) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~