Domanda

I have a question regarding reading a text file. Consider I am reading a text log file which is being continuously written by some other process. What happens if the other process tries to write to the file exactly at the same time when I am reading the file. Will my program crash? (I opened the file in read-only mode)

If the above scenario results in crash, how does the "tail -f" command works?

Is locking the file everytime I try to read is a good solution?

Actually I had a program which was using wxTextFile class to read. By default wxTextFile opens the file in read/write mode and in some cases, my program crashed. So, if I use some C functions and open the file in read-only mode, does it guarantee that the program will not crash (It is ok if some garbled value is read sometimes).

È stato utile?

Soluzione

You question is kinda/sortof entirely system dependent. First you need a system that permits multiple readers/single writer. Most systems support this, so it is largely a theoretical hurdle.

Let's assume then that you can do this.

You would have the file open for reading. Some other process has it open for writing.

If you try to read at the same time someone else is writing, that's perfectly OK. The only issue is if you are trying to read a block that the writer is writing at the same time. In that cause, the data you get is unpredictable but you should be able to read.

In short, simultaneous reads and write would not, by themselves, cause a program to crash.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top