首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

内存文件映射的有关问题

2013-04-02 
内存文件映射的问题#include sys/mman.h#include sys/types.h#include sys/stat.h#include fcntl.h

内存文件映射的问题



#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>



int main(int argc, char *argv[])
{
        int fd;
        off_t length;
        char *addr;
        char *inserted = "awdawdasdadw啊我大王的哇啊伟大我的哇awdawdawdasdawdadafdaw124234\n"; // this str will be inserted to the file
 
        fd = open("abc.txt", O_RDWR | O_CREAT, 0644);
       
        length = lseek(fd,0,SEEK_END);
        addr = (char *)mmap(NULL,4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        for (int i = 0;i < 30;i++)
{
memcpy(addr + length, inserted, strlen(inserted));
length += strlen(inserted) + 1;
}
        //printf("addr: %s", addr);
       
        munmap((void *)addr, length);
 close(fd);
}



为什么    length = lseek(fd,0,SEEK_END); 的返回值不正确? 我创建的空白文件
memcpy(addr + length, inserted, strlen(inserted)); 这里怎么崩溃了呐?
[解决办法]
偶也不知道,求解,什么错误啊。
[解决办法]
mmap并不分配空间,这种办法是不能增加文件长度的,这里的第二个参数只是表示映射区的长度,只有该长度小于文件长度才有意义。
当文件是空的话,对文件映射区进行操作就是相当于非法内存读写,报总线错误。

热点排行