File is deleted and recreated while reading. How to handle it?

Viewed 137

I have a program (let's call it the consumer) that opens and keeps reading a file. The file is created and written by another program (let's call it the producer). Some times, the file gets deleted (manually) and recreated by the producer. The problem is, the consumer doesn't know that and keeps reading the old file through the old FD, which does't have the new data. My question is, do we have a way to detect this situation in consumer (without adding some kind of communication mechanism between the consumer and the producer).

My preliminary idea is, when I open the file, I use fstat() to get the inode's number of the file. And I can use stat() later to get the inode's number again. If the inode's number is the same, then it is the same file, if the number changes, it means the file has been deleted and created already. So I can reopen the file and data can be read from the new file.

Does this idea always work? Is there any other better ways to do that. Thank you.

1 Answers

do we have a way to detect this situation in consumer

On linux you can watch with inotify the directory of the file and wait for events like moved_to or delete on that file and do an action then.

In pseudocode in shell it would look like:

watched_file=....
dir_of_watched_file=$(dirname "$watched_file")
inotifywait -m -q -e moved_to --no-newline --format "%w%f%0" "$dir_of_watched_file" |
while IFS= read -r -d '' line; do
     if [[ "$line" = "$watched_file" ]]; then
            : och, the file was moved to
            reopen "$watched_file"
     fi
done
Related