| 1 |
/* SPDX-License-Identifier: MIT-0 */ |
| 2 |
|
| 3 |
#include <stdbool.h> |
| 4 |
#include <stdio.h> |
| 5 |
#include <systemd/sd-device.h> |
| 6 |
|
| 7 |
int main(void) { |
| 8 |
__attribute__((cleanup(sd_device_enumerator_unrefp))) sd_device_enumerator *enumerator = NULL; |
| 9 |
sd_device *device; |
| 10 |
int r; |
| 11 |
|
| 12 |
/* Create a new device enumerator */ |
| 13 |
r = sd_device_enumerator_new(&enumerator); |
| 14 |
if (r < 0) { |
| 15 |
fprintf(stderr, "Failed to create device enumerator: %s\n", strerror(-r)); |
| 16 |
return 1; |
| 17 |
} |
| 18 |
|
| 19 |
/* Include only devices from the "usb" subsystem */ |
| 20 |
r = sd_device_enumerator_add_match_subsystem(enumerator, "usb", true); |
| 21 |
if (r < 0) { |
| 22 |
fprintf(stderr, "Failed to add subsystem match: %s\n", strerror(-r)); |
| 23 |
return 1; |
| 24 |
} |
| 25 |
|
| 26 |
/* |
| 27 |
* Exclude devices where the "removable" sysattr is "0" |
| 28 |
* These are typically non-removable devices like built-in USB interfaces |
| 29 |
*/ |
| 30 |
r = sd_device_enumerator_add_match_sysattr(enumerator, "removable", "0", false); |
| 31 |
if (r < 0) { |
| 32 |
fprintf(stderr, "Failed to add sysattr match: %s\n", strerror(-r)); |
| 33 |
return 1; |
| 34 |
} |
| 35 |
|
| 36 |
/* Begin enumerating matching devices */ |
| 37 |
for (device = sd_device_enumerator_get_device_first(enumerator); |
| 38 |
device; |
| 39 |
device = sd_device_enumerator_get_device_next(enumerator)) { |
| 40 |
const char *syspath; |
| 41 |
|
| 42 |
/* Get syspath for the device */ |
| 43 |
if (sd_device_get_syspath(device, &syspath) >= 0) |
| 44 |
printf("Removable USB device found: %s\n", syspath); |
| 45 |
} |
| 46 |
return 0; |
| 47 |
} |