C ++ how to check if a file is used - multi-threaded multi-processor system

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 other processes can write to for writing. If I read a file that is simultaneously being written, both the reading and the writing process give me errors (writing is incomplete, I can only get the header). So I have to check some condition before deciding whether to open this file. I use boost :: filesystem to get a list of files. I want compatibility with both Unix and Windows.

+2
source share
3 answers

You must use file locking. On Unix, this is flock ; on Windows, this is LockFile .

However, the fact that your reading process is an error probably indicates that you did not open the file in read-only mode in this process. You must specify the correct flags for read-only access or from an OS point of view, you have two authors.

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

Since you say that your system is multiprocessor (i.e. not multithreaded), you cannot use a condition variable (if it is not used in interprocess shared memory). You also cannot use one writer as a coordinator if you do not want to transfer data there through sockets or shared memory.

+2
source

From what I understand about boost::filesystem , you will not get the necessary granularity from this set of functions to perform the tasks you request. In general, you can choose two different approaches:

  • Use a synchronization mechanism, such as a semaphore with a name visible at the file system level.
  • Use file locks (i.e. fcntl or flock on POSIX systems)

Unfortunately, both approaches will be platform-oriented, or at least specific to POSIX and Win32.

+1
source

A very nice solution can be found here using the active Sutter object https://sites.google.com/site/kjellhedstrom2/active-object-with-cpp0x

It is quite advanced, but very scalable on many cores.

+1
source

Source: https://habr.com/ru/post/911682/


All Articles