Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I know if a USB device is already in use?

I am writing a C++ Linux userspace driver for a USB device using the C library libusb. I have two copies of the same device (same vendor ID and product ID) and would like to know how to handle this case.

Here are the possibilities I can think of:

  • libusb_get_device_list() returns only devices that are not currently in use

  • I can differentiate the used vs. unused devices using information of the device descriptor, using libusb_get_device_descriptor()

  • libusb_open() on the currently in-use device will fail, by returning either LIBUSB_ERROR_ACCESS or LIBUSB_ERROR


How should I deal with this? Which of the preceding options, if any, is the behaviour of libusb when dealing with many of the same devices? How can I differentiate between the in-use device and the idle one?


As @fiscblog said in his answer, "Identification is done via the device descriptor (use the serialnumber which should always be unique)". My problem here is that, in order to do so, the two drivers should communicate to know which instance is handling which device (using, for instance, a file), and I would like to avoid this. I also would like to avoid having to introduce multithreading and manage two devices with one driver, as I don't have the skills to do so in an efficient and well-controlled way (nasty race conditions ... !)

like image 944
Magix Avatar asked May 02 '17 09:05

Magix


2 Answers

The correct handling is:

  • enumerate all devices (get device list)
  • identify the requested device and open it

Identification is done via the device descriptor (use the serialnumber which should always be unique), as you discovered yourself.

How to know if a device is in use?

If a device is open, the endpoints will be bound and configured for I/O. Therefore you cannot open it again but will get the error codes you mentioned.

like image 143
fiscblog Avatar answered Oct 20 '22 01:10

fiscblog


According to the documentation on libusb_claim_interface():

Interface claiming is used to instruct the underlying operating system that your application wishes to take ownership of the interface.

so you should be able to call libusb_claim_interface() on each device and it should only succeed on the unclaimed one:

It is legal to attempt to claim an already-claimed interface, in which case libusb just returns 0 without doing anything.

like image 42
Jan-Gerd Avatar answered Oct 20 '22 00:10

Jan-Gerd