To more closely match behavior of libusb_open on other platforms, place an advisory lock on the device file descriptor.
Currently, multiple processes can open the same USB device. On Linux and Windows, USB device enumeration omits devices currently in use. A number of ports assume this behavior.
This proposed change will cause libusb_open to report an error (LIBUSB_ERROR_BUSY) if it finds an exclusive advisory lock on the device. Likewise libusb20_dev_open will also report an error (LIBUSB20_ERROR_BUSY) if if finds an exclusive advisory lock on the device.
This includes a further change to libusb_open_with_vid_pid to skip over failed attempts to the first successful call to libusb_open.
In an exteme case, current unexpected behavior in the FreeBSD implementation causes two ports to display the same device 32 times (see ports airspy and hydrasdr).
As an example, a FreeBSD host has two USB devices attached that share the same VID/PID but different serial numbers. The intent is ...
a. a first call to libusb_open_with_vid_pid returns a device handle to the first matching device - which the app keeps open.
b. a second call to libusb_open_with_vid_pid returns a device handle to the second matching device (and not the first) - which the app keeps open.
c. a third call to libusb_open_with_vid_pid returns null (and none of the other devices).
libusb_close or process exit remove the advisory lock on the device. The specific advisory lock mechanism is flock(2). A complete patch with test plan and test results is included.
Please see https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=291506 which includes source and CMakeLists.txt for the usbgrab utility. Ditto for the unit_test_libusb20_dev_open test program.