C ++如何检查文件是否在使用中 - 多线程多进程系统 [英] C++ how to check if file is in use - multi-threaded multi-process system

查看:157
本文介绍了C ++如何检查文件是否在使用中 - 多线程多进程系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++:
有没有办法检查一个文件是否被其他进程/类/设备写入?



我试图从其他进程可以访问的文件夹中读取文件进行写入。如果我读取一个同时正在写入的文件,读取和写入过程都会给我带来错误(写入不完整,我只能得到一个头文件)。
因此,在决定是否打开特定文件之前,我必须检查某种类型的条件。
我一直在使用boost :: filesystem来获取我的文件列表。我希望兼容Unix和Windows。 你必须使用文件咨询锁。在Unix中,这是 flock ,在Windows中是 LockFile



但是,您的读取进程出错的事实可能表明您没有在该进程中以只读模式打开文件。您必须为只读访问指定正确的标志,或者从操作系统的角度来看,您有两个作者。

这两个操作系统都支持读写器锁,无限的读者但是只有在没有编写者的情况下,一次最多只能有一个编写者访问。

既然你说你的系统是多进程(即不是多线程),你不能使用一个条件变量(除非它在进程间共享内存中)。除非您愿意通过套接字或共享内存来访问您的数据,否则您也不能使用单个作者作为协调者。


C++: Is there a way to check if a file has been opened for writing by another process/ class/ device ?

I am trying to read files from a folder that may be accessed by other processes for writing. If I read a file that is simultaneously being written on, both the read and the write process give me errors (the writing is incomplete, I might only get a header). So I must check for some type of condition before I decide whether to open that specific file. I have been using boost::filesystem to get my file list. I want compatibility with both Unix and Windows.

解决方案

You must use a file advisory lock. In Unix, this is flock, in Windows it is LockFile.

However, the fact that your reading process is erroring probably indicates that you have not opened the file in read-only mode in that process. You must specify the correct flags for read-only access or from the OS' perspective you have two writers.

Both operating systems support reader-writer locks, where unlimited readers are allowed, but only in the absence of writers, and only at most one writer at a time will have access.

Since you say your system is multi-process (ie, not multi thread), you can't use a condition variable (unless it's in interprocess shared memory). You also can't use a single writer as a coordinator unless you're willing to shuttle your data there via sockets or shared memory.

这篇关于C ++如何检查文件是否在使用中 - 多线程多进程系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆