Kernel32 CreateFile not giving exclusive access to USB device

1.3k views Asked by At

I am taking what was traditionally a single-instance-only application and updating it so multiple instances can execute on the same PC. Each instance will require exclusive access to a USB device. The first application instance opens a USB device with the following command (some Kernel32 wrappers for C# are in place) and gets a valid handle, as expected:

 this.handle = Kernel32.CreateFile(
       pathToUsbDevice,
       Convert.ToUInt32(FileRead.Read | FileRead.Write),
       Convert.ToUInt32(FileShare.None),
       IntPtr.Zero,
       Convert.ToUInt32(CreateDisposition.OpenExisting),
       Convert.ToUInt32(FileFlags.Overlapped),
       IntPtr.Zero);

The problem is that I then open the second instance of the application and it is able to also get a valid handle to the same device (while the first instance still has its handle). This seems incorrect to me, as my understanding of CreateFile is that it should return an invalid file handle if that device is already opened exclusively (sharing set to 0, or None).

Am I doing something wrong in CreateFile? Perhaps my assumption that it will return an invalid handle if the device is already exclusively opened is incorrect? How can I exclusively open the device for a single application instance so that other application instances cannot open it?

In case it matters, the development & test PC is Windows 7 Professional, 64-bit, building the app via Visual Studio Express 2013.

1

There are 1 answers

1
Alex Skalozub On BEST ANSWER

Looks like it is a device driver issue. I've found a similar discussion:

It's up to the driver to manage shared/non-shared, not the IO manager. So you have two choices:

  1. Mark your device exclusive in the INF (see the Exclusive registry value under http://msdn.microsoft.com/en-us/library/windows/hardware/ff546320(v=3Dvs.85).aspx )
  2. Add file create/close handlers in your driver and manage the count of clients yourself

You might want to use some other approach to ensure only one instance of your app is accessing device (like using a named global mutex to guard device access).