开发者

Reading a file in a process while a process is writing in c++

I have a file increasing by time, and need to read the file without any race condition or something in another process in C++ on Windows.

Wr开发者_开发问答iting a file is given, and there is no room I can play with it. Only thing I can do is reading it gracefully.

Do you have any idea to handle this case well?

TIA


In Win32 you would have to make sure that every writer opens the file with at least read share access, and every reader opens the file with at least write share access. Further sharing would be required if you have >1 reader or >1 writer.

See here for CreateFile docs, dwShareMode parameter.


You'll almost certainly need to use CreateFile (In both processes) to allow sharing the file at all. If the writing application opens the file in exclusive sharing mode and keeps it open, the reading application won't be able to open the file at all.

From there, preventing race conditions is fairly straightforward: each process will typically use LockFile or LockFileEx to lock a section of the file for exclusive access while it uses data in that section of the file. In general, you want to keep that period of time as short as possible, so you'll lock the section, read/write, and unlock, all about as quickly as possible (i.e., without doing anything else, if you can avoid it).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜