Is it possible to write to a mmap'd file without getting a bus error

227 Views Asked by At

I'm trying to monitor a file that I create for when the contents change from 0 to 1. This code create the file and maps it fine, I then spin, waiting for the contents of *map to change from '0' to '1'.

However as soon as I run echo 1 > file.dat the code crashes with a Bus Error.

I am assuming this is because a new file is being created by echo (or anything else I try) and the mmap is no longer pointing to something relevant. Is there any way to make this work?

int fd = open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);

write(fd, "0", 1)

char* map = static_cast<char*>(mmap(0, 1, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
1

There are 1 best solutions below

8
On BEST ANSWER

echo 1 > the_file does the following:

  1. Truncate the_file to 0 bytes.
  2. Append the characters 1 and \n to the_file

In between steps 1 and 2, the file has length 0.

(Step 1 is performed by the shell, when it interprets the redirection >the_file. Step 2 is then performed by the echo command, so there could be a significant amount of time between the two.)

If you want to overwrite one character of the file, you can use dd:

echo 1 | dd of=the_file bs=1 count=1 conv=notrunc