Saturday, April 23, 2016

C++ Check if file is locked using filehandle?

Leave a Comment

Given I have a list of all file handles of all processes, how could I find out which of these handles are actually locking a file?

From what I understand I could simply try to open the files and try to get all the permissions and if something goes wrong I'd know it is locked. But that sound extremely inefficient. I mean I already have the handles is there no way to check which permissions the handles have?

Preferably I'd like to see a solution that works on Windows XP and above.

I already searched through the GetFileInformationByHandleEx function, but I couldn't find anything about access permissions. :/

Edit: I don't need real-time information on the file lock. The files that I'm planning to work on will either be locked until certain applications are closed or not be locked at all.

2 Answers

Answers 1

This question is a duplicate of Win32 files locked for reading: how to find out who's locking them.

Also, Hans Passant's commentary is correct: querying the locked state of any Win32 file gives stale information. Disregarding this warning will cause hard-to-find bugs.

If you control all bits of code that you think will access the files, it's better to use a named pipe for interprocess communication, instead of querying locked files.

Answers 2

You can use NtQueryObject API to get information about the handle including the following:

ULONG Attributes; ACCESS_MASK GrantedAccess; 

Or you can access the same information using NtQueryInformationFile using FileModeInformation and FileAccessInformation values for FileInformationClass parameter.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment