I’m reading some files from the procfs every few seconds, and displaying the information. Instead of opening and closing the files each time, I’m maintaining open file handles and closing them when I’m finished. The problem is that I’m consistently getting old data. The information gathered from the first read is returned in subsequent reads, and I’ve confirmed that the procfs files are indeed changing.
The only workaround I’ve found is to do an fflush() before a rewind() when reading the data. This works, but I don’t understand why. I know that if I have two programs reading and writing to the same file, an fflush() would be necessary on the PRODUCER side to allow for these changes to be seen by the consumer. Here I’m doing a fflush() on the consumer side and it works. Doesn’t the producer and consumer have different file handles, and so a fflush() in the consumer does not fflush() data written by the producer?
Any ideas why I’m getting stale data without fflush(), and up-to-date information using fflush()?
File streams are usually buffered meaning that they are copied to memory before reading to avoid locking them from other processes. You must ensure that your Stream is un-buffered to continually retrieve the information from the hard disk. To do that use
setbuf (stream,NULL );to ensure that your buffer is cleared.You can read about setbuf here:
http://www.cplusplus.com/reference/clibrary/cstdio/setbuf/
The reason I assumed that your stream is buffered is because
fflush(stream)clears a buffered stream.You can read about that here:
http://www.cplusplus.com/reference/clibrary/cstdio/fflush/