简体   繁体   English

从2个进程读取/写入相同文件

[英]Read/write same file from 2 processes

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? 如果以上情况导致崩溃,“ tail -f”命令如何工作?

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. 实际上,我有一个使用wxTextFile类进行读取的程序。 By default wxTextFile opens the file in read/write mode and in some cases, my program crashed. 默认情况下,wxTextFile以read/write模式打开文件,在某些情况下,我的程序崩溃了。 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). 因此,如果我使用一些C函数并以只读模式打开文件,是否可以保证程序不会崩溃(如果有时读取一些乱码,也可以)。

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. 简而言之,同时读取和写入本身不会导致程序崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM