Chinaunix首页 | 论坛 | 博客
  • 博客访问: 101230
  • 博文数量: 32
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 75
  • 用 户 组: 普通用户
  • 注册时间: 2015-07-16 12:56
文章分类

全部博文(32)

文章存档

2017年(7)

2016年(25)

我的朋友

分类: 网络与安全

2016-04-07 17:22:20

此代码来自...[反正不是自己写的]
nginx使用了mmap()来操作共享内存,但是没有使用文件指针,对于不使用文件指针的第二个进程怎么获取内存

点击(此处)折叠或打开

  1. /**************************************************************************************/
  2. /*简介:mmap_write共享内存,写操作子程序 */
  3. /*************************************************************************************/
  4. #include <sys/mman.h>
  5. #include <sys/types.h>
  6. #include <fcntl.h>
  7. #include <unistd.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <stdio.h>

  11. typedef struct
  12. {
  13.  char name[4];
  14.  int age;
  15. }people;

  16. int main(int argc, char** argv)
  17. {
  18.  int fd,i;
  19.  people *p_map;
  20.  char name[4];
  21.  if (argc != 2)
  22.  {
  23.     perror("usage: mmap_write ");
  24.     return 1;
  25.  }

  26.  fd=open(argv[1],O_CREAT|O_RDWR|O_TRUNC,00777);
  27.  lseek(fd,sizeof(people)*5-1,SEEK_SET);
  28.  write(fd,"",1);
  29.  
  30.  p_map = (people*) mmap( NULL,sizeof(people)*10,\
  31.   PROT_READ|PROT_WRITE,MAP_SHARED,fd,0 );
  32.  close( fd );
  33.  name[0] = 'a';
  34.  name[1] = '\0';
  35.  for(i=0; i<10; i++)
  36.  {
  37.   name[0] ++;
  38.   memcpy( ( *(p_map+i) ).name, &name,sizeof(name) );
  39.   ( *(p_map+i) ).age = 20+i;
  40.  }
  41.  printf(" initialize over \n ");
  42.  sleep(10);

  43.  munmap( p_map, sizeof(people)*10 );
  44.  printf( "umap ok \n" );
  45.  return 0;
  46. }


点击(此处)折叠或打开

  1. /**************************************************************************************/
  2. /*简介:mmap_read共享内存,读操作子程序 */
  3. /*************************************************************************************/
  4. #include <sys/mman.h>
  5. #include <sys/types.h>
  6. #include <fcntl.h>
  7. #include <unistd.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>

  10. typedef struct
  11. {
  12.  char name[4];
  13.  int age;
  14. }people;

  15. int main(int argc, char** argv)
  16. {
  17.  int fd,i;
  18.  people *p_map;
  19.  if (argc != 2)
  20.  {
  21.   perror("usage: mmap_read ");
  22.   return 1;
  23.  }
  24.  fd=open( argv[1],O_CREAT|O_RDWR,00777 );
  25.  p_map = (people*)mmap(NULL,sizeof(people)*10,\
  26.   PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
  27.  close(fd);
  28.  for(i = 0;i<10;i++)
  29.  {
  30.   printf( "name: %s age %d;\n",(*(p_map+i)).name, (*(p_map+i)).age );
  31.  }
  32.  munmap( p_map,sizeof(people)*10 );
  33.  return 0;
  34. }

阅读(1259) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~