我是linux_man 发表于 2015-07-22 22:17

mmap函数的第二个参数映射区长度,比文件长度小情况下的问题

本帖最后由 我是linux_man 于 2015-07-22 22:27 编辑

    12 main(){
   13         struct stat buf;
   14         int fd,pid;
   15         char *p;
   18         if((fd=open("abc",O_CREAT|O_RDWR))<0){
   19               printf("open error\n");
   20         }
   21         ftruncate(fd,5);
   22         if(fstat(fd,&buf)<0){
   23               printf("stat error\n");
   24         }
   25         printf("size is %d\n",(size_t)(buf.st_size));
   27         p=(char *)mmap(NULL, 2, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
   31         strcpy(p,"123456");
   35         close(fd);
   36         if((pid=fork())<0){
   37               printf("fork error");
   38         }
   39         else if(pid==0){
   40               int fd2;
   41               char *q;
   43               if((fd2=open("abc",O_RDWR))<0){
   44                         printf("open error\n");
   45               }
   47               q=(char *)mmap(NULL, 2, PROT_READ|PROT_WRITE, MAP_SHARED, fd2, 0);
   48               printf("child:%s\n",q);
   51               exit(EXIT_SUCCESS);
   52         }
   53
   54         sleep(5);
   55         printf("father:%s\n",p);
   56
   57 }
18--21父进程中打开文件abc,大小为5字节
27通过mmap将文件映射到内存中,mmap第二个参数是2
31给mmap得到的指针空间赋值字符串“123456”
43--47在子进程中,通过mmap打开共享内存,mmap第二个参数依然是2

48为什么打印的结果是123456呢?此时文件abc里的内容是12345。

mmap()第二个参数len的意思是将文件从偏移位处映射len个长度到进程的地址空间中,可是我父子进程中,mmap第二个参数给的都是2,小于文件长度5,为什么我在子进程中读取共享内存的内容,能读到“123456”这么多个字节内容呢?这样,这个len有什么用啊,即使我写入内存的内容大于len的长度,进程间照样能完全读到啊?
谁能帮我解惑!

framily 发表于 2015-07-23 15:59

发现楼主一个问题。。open,失败,没有返回,这样的话,判断了也没什么意思

framily 发表于 2015-07-23 16:14

回复 2# framily


    The contents of a file mapping (as opposed to an anonymous mapping; see MAP_ANONYMOUS
       below), are initialized using length bytes starting at offset offset in the file(or
       otherobject)referredto by the file descriptor fd.offset must be a multiple of
       the page size as returned by sysconf(_SC_PAGE_SIZE).

framily 发表于 2015-07-23 16:26

The munmap() system call deletes the mappings for the specifiedaddressrange,and
       causesfurtherreferencesto addresses within the range to generate invalid memory
       references.The region is also automatically unmapped whentheprocessistermi-
       nated.On the other hand, closing the file descriptor does not unmap the region.

调用munmap之前不会将内容写入文件,但是缓冲区部分里面此时应该是123456,

framily 发表于 2015-07-23 16:29

回复 1# 我是linux_man


    MAP_SHARED //与其它所有映射这个对象的进程共享映射空间。对共享区的写入,相当于输出到文件。直到msync()或者munmap()被调用,文件实际上不会被更新。

我是linux_man 发表于 2015-07-24 13:12

回复 5# framily
可是我上面的程序也没munmap啊,文件里也是有数据的?


   
页: [1]
查看完整版本: mmap函数的第二个参数映射区长度,比文件长度小情况下的问题