Link to home
Start Free TrialLog in
Avatar of Nobuo Miwa
Nobuo Miwa

asked on

How do I know who is locking the file in my C++ codes ?

Hello Experts,

I'm looking for C++ sample code to determine WHO IS LOCKING THE FILE ?
I want to know the process ID of locking specific file.
I know that Process Explorer can do that.
I want to do it in my C++ program.

I guess OpenProcess() and DuplicateHandle() are the key, but I don't know how to implement.

Windows 7 32bit

Please advice
Nobuo Miwa
Avatar of AielloJ
AielloJ
Flag of United States of America image

NobMiwa,

I don't believe it's possible since file handle information is stored in kernel space.  There are function calls that will tell you the name of the application that has the file open ( IFileIsInUse::GetAppName() ) but not the user.  Even then, the other application opening the file would have to have been written to be cooperative.

Best regards,

AielloJ
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Nobuo Miwa
Nobuo Miwa

ASKER

Hello,

Thank you for the information.

I found the one of solution, it works fine on my C++Builder XE2.
But I don't know that is correct...

	HANDLE hProcess = OpenProcess(
				PROCESS_ALL_ACCESS,
				FALSE,
				pid);
	HANDLE handle;
	for(int t=1;t<1000;t++){
		// Duplicate the handle
		if( ::DuplicateHandle(hProcess,
					 (HANDLE)t,
					 GetCurrentProcess(),
					 &handle,
					 GENERIC_READ,
					 FALSE,
					 0) ) {

			wchar_t  path[1024];
			ZeroMemory(path,sizeof(path));
			DWORD rt = GetFinalPathNameByHandle(handle,
			     path,
			     sizeof(path)-1,
			     FILE_NAME_NORMALIZED);
			if (rt>0) {
			    // fullpath here
			}
		}
	}

Open in new window

Might work, to find a file's name but: How do you obtain the PID you are using in the above? That's what my example does ;o)
Hello,

I customize my code that is using NtQuerySystemInformation and it works.
So now I could get correct file handle now.

I got process ID list from followings..

Process32FirstW(hSnap, &pe32);
Process32FirstW(hSnap, &pe32);

Thank you for the hint.

Nobuo Miwa
Thank you !