开发者

Writing and reading from the same text file with different scripts

This is a question which isn't linked to any practical situation I'm in, but it always bugged me.

What could go wrong if I have one script reading and appending lines in one text file and another script reading from the same file?

开发者_高级运维

I know that when a script opens a text file it's working with the version of that file from the moment it has been opened, not considering following edits. I want both script to be working with the latest possible version (I recon it won't be real-time) of the text file.

I guess one way of putting the question is: which is the best way to handle said scripts? When should I close and open the file in the first one?


I know that when a script opens a text file it's working with the version of that file from the moment it has been opened, not considering following edits

This is wrong statement. For example try following command in Unix:

tail -f <some file>

And then try to add lines to that file. tail command will follow your additions. (assuming you do flush periodically when writing).


One issue you could run into is the file being locked by one process when the other tries to access it. To avoid this you should open, read in the entire file (or write the new line) and close it straight away.

As well you may want to add error handling around the open so if it fails because the file is locked it can try again after a short pause.


The tail command would do what you want, else you'd need to open, edit, save, close from one script then the other opens, reads, closes and so on. The scripts would have to take turns

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜