使用mmap遇到总线错误bus error

先简单描绘一下错误发生的场景:

#define MMAP_BUFF_SIZE 4096
struct Message
{
    int    len;
    char   data[1024];      
};

int fd = open("./test",O_RDWR | O_CREAT);
lseek(fd,MMAP_BUFF_SIZE,SEEK_SET);
Message* m = NULL;
m = (Message*)mmap(NULL,MMAP_BUFF_SIZE,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
m->len = 3;        //发生总线错误
strcpy(m->data,"123");

发生错误的原因是因为mmap不能去扩展一个内容为空的新文件,因为大小为0,所有本没有与之对应的合法的物理页,不能扩展。

所以只需要在新创建的空文件中先写入一些数据即可

完整场景

#define MMAP_BUFF_SIZE 4096
struct Message
{
    int     len;
    char     data[1024];
};
struct MM
{
    int     a;
    int     b;
};

int main()
{
    int fd = open("./test",O_RDWR | O_CREAT);
    if(fd == -1)
    {
        perror("open file error");
        exit(1);
    }
    write(fd,"1",1);
    lseek(fd,MMAP_BUFF_SIZE,SEEK_SET);
    pid_t pid = fork();
    if(pid == -1)
    {
        perror("fork error");
        close(fd);
        exit(1);
    }
    
    if(pid > 0)
    {//parent
        Message* m = (Message*)mmap(NULL,MMAP_BUFF_SIZE,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
        MM d;
        int k = 1;
        while(1)
        {
            d.a = k;
            d.b = k + 2;
            m->len = sizeof(MM);
            memcpy(m->data,(char*)&d,m->len);
            if(k == 12)
                break;
            sleep(1);
            k++;
        }  
        wait(NULL);
        munmap((void*)m,MMAP_BUFF_SIZE); 
        remove("./test");
    }else
    {//child
        Message* m = (Message*)mmap(NULL,MMAP_BUFF_SIZE,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
        MM* d = NULL;
        while(1)
        {
            d = (MM*)m->data;
            cout<a<<" "<b<a == 10)
                break;
            sleep(1);
        }
        munmap((void*)m,MMAP_BUFF_SIZE);    
    }
    close(fd);  
    return 0;
}

 

你可能感兴趣的:(linux)