From 32e063de667e4222aeda31a05714572d8263c8e4 Mon Sep 17 00:00:00 2001 From: Tormod Volden Date: Mon, 12 Aug 2024 21:36:37 +0200 Subject: [PATCH] examples/hotplugtest: Allow multiple devices attaching If no device ID is specified, and for instance a hub is plugged, many devices will be attached (and later detached) at the same time. The old code counting only 2 events would then exit prematurely. By counting attach and detach events separately, we preserve the old behaviour in the single-device case, but also allow more complex sequences to be handled in a way that mostly appears intuitive. This is not fool-proof, and we can still end up leaving after a surprise detachment of a "pre-existing" device while we have one of the "new" devices open. In this case print a warning. References #1455 Signed-off-by: Tormod Volden --- examples/hotplugtest.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/examples/hotplugtest.c b/examples/hotplugtest.c index 3e092cf45..391754b3b 100644 --- a/examples/hotplugtest.c +++ b/examples/hotplugtest.c @@ -23,7 +23,8 @@ #include "libusb.h" -int done = 0; +int done_attach = 0; +int done_detach = 0; libusb_device_handle *handle = NULL; static int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev, libusb_hotplug_event event, void *user_data) @@ -56,7 +57,7 @@ static int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev, libusb_strerror((enum libusb_error)rc)); } - done++; + done_attach++; return 0; } @@ -85,7 +86,7 @@ static int LIBUSB_CALL hotplug_callback_detach(libusb_context *ctx, libusb_devic handle = NULL; } - done++; + done_detach++; return 0; } @@ -130,7 +131,7 @@ int main(int argc, char *argv[]) return EXIT_FAILURE; } - while (done < 2) { + while (done_detach < done_attach || done_attach == 0) { rc = libusb_handle_events (NULL); if (LIBUSB_SUCCESS != rc) printf ("libusb_handle_events() failed: %s\n", @@ -138,6 +139,7 @@ int main(int argc, char *argv[]) } if (handle) { + printf ("Warning: Closing left-over open handle\n"); libusb_close (handle); }