GeezerVison is showing github.com — Examples: Fix device leak in hotplugtest · Raghuvardhan-Reddy78/libusb@3037616
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: examples/hotplugtest.c +21-3Lines changed: 21 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
24 | 24 | #include "libusb.h" |
25 | 25 |
|
26 | 26 | int done = 0; |
27 | | -libusb_device_handle *handle; |
| 27 | +libusb_device_handle *handle = NULL; |
28 | 28 |
|
29 | 29 | static int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev, libusb_hotplug_event event, void *user_data) |
30 | 30 | { |
@@ -38,7 +38,15 @@ static int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev, |
38 | 38 |
|
39 | 39 | printf ("Device attached: %04x:%04x\n", desc.idVendor, desc.idProduct); |
40 | 40 |
|
41 | | - libusb_open (dev, &handle); |
| 41 | + if (handle) { |
| 42 | + libusb_close (handle); |
| 43 | + handle = NULL; |
| 44 | + } |
| 45 | + |
| 46 | + rc = libusb_open (dev, &handle); |
| 47 | + if (LIBUSB_SUCCESS != rc) { |
| 48 | + fprintf (stderr, "Error opening device\n"); |
| 49 | + } |
42 | 50 |
|
43 | 51 | done++; |
44 | 52 |
|
@@ -49,9 +57,13 @@ static int LIBUSB_CALL hotplug_callback_detach(libusb_context *ctx, libusb_devic |
49 | 57 | { |
50 | 58 | printf ("Device detached\n"); |
51 | 59 |
|
52 | | - libusb_close (handle); |
| 60 | + if (handle) { |
| 61 | + libusb_close (handle); |
| 62 | + handle = NULL; |
| 63 | + } |
53 | 64 |
|
54 | 65 | done++; |
| 66 | + |
55 | 67 | return 0; |
56 | 68 | } |
57 | 69 |
|
@@ -100,5 +112,11 @@ int main(int argc, char *argv[]) |
100 | 112 | printf("libusb_handle_events() failed: %s\n", libusb_error_name(rc)); |
101 | 113 | } |
102 | 114 |
|
| 115 | + if (handle) { |
| 116 | + libusb_close (handle); |
| 117 | + } |
| 118 | + |
103 | 119 | libusb_exit (NULL); |
| 120 | + |
| 121 | + return EXIT_SUCCESS; |
104 | 122 | } |
Collapse file
Copy file name to clipboard +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
|
1 | | -#define LIBUSB_NANO 10947 |
| 1 | +#define LIBUSB_NANO 10948 |