简体   繁体   中英

Unable to access data structure after `open()` and `mmap()` - Bus Error

I'm writing a fork() based server and I need to have an array shared between the parent process and its' forked children. I was specifically requested to use a file and mmap() for the implementation so I will be able to use fcntl() locks easily later on.

For some reason, when I try to execute the code below, I'm getting Bus Error on the line struct_array[i].number = -1; .

if ((fd = open("/tmp/tmp-file", O_RDWR | O_CREAT | O_TRUNC, 777)) == -1) {
    perror("open");
}

struct my_struct *struct_array = mmap(NULL, struct_size, PROT_READ | PROT_WRITE,
    MAP_SHARED, fd, 0);

if (struct_array == MAP_FAILED) {
    perror("mmap");
}

for (i = 0; i < CLIENTS_SIZE; i++) {
    struct_array[i].number = -1;
}

I went over the man pages again and again but there's must be something I'm missing.

Accessing an address within a mapped memory range yields bus error if the corresponding offset falls beyond the end of file.

In this particular case the file size is zero, you should make the file at least struct_size bytes long (use ftruncate).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM