简体   繁体   中英

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

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:

  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

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