'How do I make `read` fail when another process writes to the file?

Lets say I open up a binary file (or text as binary) and read 16K bytes. Another file opens the process and truncates it, appends, or changes bytes I haven't read (or already read)

Would there be a way to have read fail? Currently when I get to the end of the file I do a stat and check if the modification time matches the time I started with but I rather fail sooner than later



Solution 1:[1]

You could use a critical section. I think that's what Nate Eldredge Suggested.

Enter critical section
    Read file
Leave critical section

Now you can write

Then your "read" will not fail, but there will be no more reason to do so.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tycho