How to check if a file is used by another process in C++?

1.8k Views Asked by At

I need to check if a file is currently opened by another process, e.g. a text editor (but needs to apply to everything else too).

I tried using std::ofstream::is_open() etc., but this did not work. I could open the file in my text editor while my program was checking if it was open. The program saw it as a closed file and went on. Only if I opened it as another ofstream would this work.

I'm using the filesystem library to copy files and they may only be copied (and later removed) if the file is not currently written to by another process on the client server.

Really curious about this one. Been wondering this for quite some time but never found a good way for it myself.

I'm currently making a program that needs to be able to run on both linux and windows. every 5 seconds it copies all files from directory a,b,c,d to x. This can be set by the client in rules. after it copied everything. all the files may be removed. After a day (or whatever the client tells the program) all those files from x need to be zipped and archived on location y. Hence the problem, files may only be deleted (and copied) if the other programs that place all the files in directories a,b,c,d are not touching that specific file right now. Hope that makes the question clearer.

And before anybody starts. Yes I know about the data race condition. I do not care about this for now. The program does absolutely nothing with the contents of a file. And after a file is closed by the other process, it will be closed forever.

1

There are 1 best solutions below

2
On

I need to check if a file is currently opened by another process

This is heavily operating system specific (and might be useless)

So read first a good textbook on operating systems.

On Linux specifically you might use inotify(7) facilities, or /proc/ pseudo-file system (see proc(5)), or perhaps lsof(8). They work only for local file systems (not remote ones, like NFS). See also Advanced Linux Programming and syscalls(2).

And you could have surprises (e.g. a process being scheduled so quickly that removes a file that you won't have time to do anything)

For Windows take more time to read its documentation.

I'm currently making a program that needs to be able to run on both linux and windows. every 5 seconds it copies all files from directory a,b,c,d to x.

You might look, at least for inspiration, inside the source code of rsync.

I don't understand what your actual problem is, but rsync might be part of the solution and is rumored to run on both Windows and Linux