From 8313b1f5799c27cf05cc91f1a29fdcb870a515b1 Mon Sep 17 00:00:00 2001 From: Tormod Volden Date: Mon, 12 Aug 2024 23:27:32 +0200 Subject: [PATCH] examples/hotplugtest: Close old device only if new one was opened We want to keep only one device open for simplicity, but instead of closing the last opened device already before /trying/ to open a new one, close it only if the new one was opened successfully. This way we may keep the device open longer, and in the simple case where no later arriving devices could be opened, until it is detached again. Signed-off-by: Tormod Volden --- examples/hotplugtest.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/examples/hotplugtest.c b/examples/hotplugtest.c index 391754b3b..8904cc848 100644 --- a/examples/hotplugtest.c +++ b/examples/hotplugtest.c @@ -30,6 +30,7 @@ libusb_device_handle *handle = NULL; static int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev, libusb_hotplug_event event, void *user_data) { struct libusb_device_descriptor desc; + libusb_device_handle *new_handle; int rc; (void)ctx; @@ -46,13 +47,13 @@ static int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev, libusb_strerror((enum libusb_error)rc)); } - if (handle) { - libusb_close (handle); - handle = NULL; - } - - rc = libusb_open (dev, &handle); - if (LIBUSB_SUCCESS != rc) { + rc = libusb_open (dev, &new_handle); + if (LIBUSB_SUCCESS == rc) { + if (handle) { + libusb_close (handle); + } + handle = new_handle; + } else { fprintf (stderr, "No access to device: %s\n", libusb_strerror((enum libusb_error)rc)); }