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));
echo 1 > the_file
does the following:the_file
to 0 bytes.1
and\n
tothe_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 theecho
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
: