How to read the content of file while the same file is writing the log entry in thread. I wanna to develop log viewer for my tool (like tail.exe)
views:
61answers:
3You should not both read and write from/to the same file at the same time, you should use mutex to avoid race conditions. You can declare a global mutex variable and lock/unlock mutex while reading and writing respectevly. This is well known Producer-consumer Problem (Aka. Reader/Writer Problem).
You shouldn't have any problems, certainly on Linux type systems. The writer opens the file for writing. The reader opens the file for reading. The OS should make sure that all operations are atomic.
For a logging application it is probably better to use raw file i/o (open/read/write etc rather than fpen/fread etc) as the buffering doesn't help; at least make sure that the writer flushes the output so that it is written straightaway.
I tried using fstream in thread. It is able to read by while second writing unable to read that updated content in the file