tags:

views:

145

answers:

4

I see that standard C has no way of telling if a file is already opened in another process. So the answer should contain several examples for each platform. I need that check for Visual C++ / Windows though.

A: 

Any such check would be inherently racy. Another process could always open the file between the point where you did the check and the point where you accessed the file.

caf
+1  A: 
Carl Smotricz
It is possible to do this in Windows. The Sysinternals handle.exe tool does it, for example. http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx
invariant
+1, thanks! I just updated my answer to reflect this.
Carl Smotricz
+1  A: 

There's no way tell, unless the other process explicitly forbids access to the file. In MSVC, you'd do so with _fsopen(), specifying _SH_DENYRD for the shflag argument. The notion of being interested whether a file is opened that isn't otherwise locked is deeply flawed on a multitasking operating system. It might be opened a microsecond after you'd have found it wasn't. That's also the reason that Windows doesn't have a IsFileLocked() function.

If you need synchronized access to files, you'll need to add this with a named mutex, use CreateMutex().

Hans Passant
Thanks. For Windows this works and really helped my problem. The rest is for other people seeking an answer for other platforms may be.
winlin
A: 

The answers so far should tell you that finding out the information you've asked for is tricky, non-portable, and often inherently unreliable. So, from my perspective, the real answer is don't do that. Try to find a way to think about your real problem so that this question doesn't arise.

Dale Hagglund