Bus Error when writing to mmaped data
Asked Answered
A

2

5

When I first made this project last semester, the code worked fine. Now I get a bus error when the mmapped memory to share between processes is being written to and I'm not sure why it is not working anymore.

Account_Info *mapData()
{
    int fd;
    //open/create file with read and write permission and check return value
    if ((fd = open("accounts", O_RDWR|O_CREAT, 0644)) == -1)
    {
            perror("Unable to open account list file.");
            exit(0);
    }

    //map data to be shared with different processes
    Account_Info *accounts = mmap((void*)0, (size_t) 100*(sizeof(Account_Info)), PROT_WRITE,
    MAP_SHARED, fd, 0);

    int count= 0;

    //loop to initialize values of Account_Info struct
    while (count != 20)
    {
            //bus error occurs here
            accounts[count].CurrBalance= 0;
            accounts[count].flag = 0;
            int i = 0;
            while (i != 100)
            {
                    //place NULL terminator into each element of AccName
                    accounts[count].AccName[i]= '\0';
                    i++;
            }

            count++;
    }

    close(fd);
    return accounts;
}
Accumulate answered 9/10, 2016 at 1:22 Comment(0)
A
6

A documented cause for SIGBUS with mmap is

Attempted access to a portion of the buffer that does not correspond to the file (for example, beyond the end of the file, including the case where another process has truncated the file).

My guess is that the accounts file didn't exist, so open with O_CREAT created it. But it has zero size, so any attempt to read or write through the mapping will fault. You need to fill the file with enough zeroes (or something else) to cover the mapping, for example using ftruncate.

Ankerite answered 9/10, 2016 at 1:34 Comment(0)
M
3

You will get SIGBUS if you attempt to write past the mapped region of the file.

Chances are pretty good that your backing store file accounts is truncated/too short. (e.g.) if the file has space for 10 struct entries and you write to the 11th, you'll get SIGBUS

Do an fstat to get st_size and compare this against the length parameter you're giving to mmap

You may want to consider using ftruncate to extend the file before doing mmap

Meadowlark answered 9/10, 2016 at 1:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.