C++ – Find out which process has an exclusive lock on a USB device handle

c++devicehidusbwinapi

I have a library that reads/writes to a USB-device using CreateFile() API. The device happens to implement the HID-device profile, such that it's compatible with Microsoft's HID class driver.

Some other application installed on the system is opening the device in read/write mode with no share mode. Which prevents my library (and anything that consumes it) from working with the device. I suppose that's the rub with being an HID-compatible device — other driver software (mice, controllers, PHIDGETS, etc) can be uncooperative.

Anyway, the device file path is of the form:

1: "\\?\hid#hpqremhiddevice&col01#5&21ff20e7&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}".

2: "\\?\hid#vid_045e&pid_0023#7&34aa9ece&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}".

3: "\?\hid#vid_056a&pid_00b0&col01#6&5b05f29&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}".

And I'm trying to open it using code, like:

//  First, open it with minimum permissions, this device may not be ours.
//  we'll re-open it later in read/write
hid_device_ref = CreateFile(
    device_path, GENERIC_READ,
    0, NULL, OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL, NULL);

I've considered a tool like FileMon or Process Monitor from SysInternals. But I can't seem to get it to report usage on device file handles like the one listed above.

Best Solution

Have you tried the tool called handle from sysinternals?

Anyway, neither windows does this (display the name of the application that locked the device): when you try to eject an USB device, Windows just says that the device is currently in use and cannot be remove right now.

Related Question