免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1307 | 回复: 1
打印 上一主题 下一主题

请教 mmap ... [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2003-12-12 09:40 |只看该作者 |倒序浏览
从输出看mmap确实映射了,但myread读到的同mywrite所写的并不实时对应,有什么办法改吗,即使阻塞也可以,和msync没关吧应该?先谢过
  1. (myread.c)
  2. #include
  3. int main()
  4. {
  5.         int fd;
  6.         int *shm;
  7.        
  8.         fd = open("data.tmp",O_CREAT|O_RDWR,00777);
  9.         if(fd<0)
  10.         {
  11.                 ...
  12.         }
  13.         int len;
  14.         len = lseek(fd,0,SEEK_END);
  15.         if(len<1)
  16.         {
  17.                 lseek(fd,1,SEEK_SET);
  18.                 write(fd,'1',1);
  19.         }
  20.        
  21.         shm = mmap(NULL,1,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
  22.         if(shm == (int *)-1)
  23.         {
  24.                 ....
  25.         }
  26.        
  27.         while(1)
  28.         {
  29.                 printf("%d read: %d\n",getpid(),*shmq);
  30.         }
  31. }
  32. +++++++++++++++++++++
  33. (mywrite.c)
  34. #include
  35. int main()
  36. {
  37.         int fd;
  38.         int *shm;
  39.        
  40.         fd = open("data.tmp",O_CREAT|O_RDWR,00777);
  41.         if(fd<0)
  42.         {
  43.                 ...
  44.         }
  45.         int len;
  46.         len = lseek(fd,0,SEEK_END);
  47.         if(len<1)
  48.         {
  49.                 lseek(fd,1,SEEK_SET);
  50.                 write(fd,'1',1);
  51.         }
  52.        
  53.         shm = mmap(NULL,1,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
  54.         if(shm == (int *)-1)
  55.         {
  56.                 ....
  57.         }
  58.        
  59.         while(1)
  60.         {
  61.                 *shm = (*shm+1)%10000;
  62.                 printf("%d read: %d\n",getpid(),*shmq);
  63.         }
  64. }
复制代码



输出:
1024 write :4
1024 write :5
1024 write :6
1024 write :7 ....


1023 read : 4
1023 read : 4
.
.
1023 read : 2206
1023 read : 2206
.
.

--------------------------------------
MAP_SHARED : share this mapping with all other process that map this obhect .
storing to the region is equivalent to writing to the file .the file may not
actually be updated until msync or munmap are called.

论坛徽章:
1
荣誉版主
日期:2011-11-23 16:44:17
2 [报告]
发表于 2003-12-12 15:55 |只看该作者

请教 mmap ...

你两个进程之间没有做同步,当然会不一致了。

用信号灯,或者文件锁什么的,做同步吧。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP