Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bus error opening and mmap'ing a file

I want to create a file and map it into memory. I think that my code will work but when I run it I'm getting a "bus error". I searched google but I'm not sure how to fix the problem. Here is my code:

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

int main(void)
{
    int file_fd,page_size;
    char buffer[10]="perfect";
    char *map;

    file_fd=open("/tmp/test.txt",O_RDWR | O_CREAT | O_TRUNC ,(mode_t)0600);

    if(file_fd == -1)
    {
        perror("open");
        return 2;
    }

    page_size = getpagesize();

    map = mmap(0,page_size,PROT_READ | PROT_WRITE,MAP_SHARED,file_fd,page_size);

    if(map == MAP_FAILED)
    {
        perror("mmap");
        return 3;
    }

    strcpy(map, buffer);

    munmap(map, page_size);
    close(file_fd);
    return 0;
}
like image 803
begin_EN Avatar asked Dec 14 '13 20:12

begin_EN


People also ask

What is a mmap file?

An . mmap file is a file format created by Mindjet for it's mind mapping software, MindManager. These mmap files are also referred to as memory files, mind maps, etc. They can contain many different elements such as images, icons, equations, text, symbols, and more.

What does mmap actually do?

In computing, mmap(2) is a POSIX-compliant Unix system call that maps files or devices into memory. It is a method of memory-mapped file I/O. It implements demand paging because file contents are not immediately read from disk and initially use no physical RAM at all.

Does mmap load file into memory?

Yes, mmap creates a mapping. It does not normally read the entire content of whatever you have mapped into memory. If you wish to do that you can use the mlock/mlockall system call to force the kernel to read into RAM the content of the mapping, if applicable.

What is mmap shared memory?

MMAP is a UNIX system call that maps files into memory. It's a method used for memory-mapped file I/O. It brings in the optimization of lazy loading or demand paging such that the I/O or reading file doesn't happen when the memory allocation is done, but when the memory is accessed.


1 Answers

You are creating a new zero sized file, you can't extend the file size with mmap. You'll get a bus error when you try to write outside the content of the file.

Use e.g. fallocate() on the file descriptor to allocate room in the file.

Note that you're also passing the page_size as the offset to mmap, which doesn't seem to make much sense in your example, you'll have to first extend the file to pagesize + strlen(buffer) + 1 if you want to write buf at that location. More likely you want to start at the beginning of the file, so pass 0 as the last argument to mmap.

like image 161
nos Avatar answered Sep 21 '22 17:09

nos