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.
Looks like it is a device driver issue. I've found a similar discussion:
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).