1. 程式人生 > >實時叠代所有連接的 USB 硬件設備

實時叠代所有連接的 USB 硬件設備

add 字典 實時 destroy code 子類 叠代 run mode

// // main.c // DriverIterator // #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOKitLib.h> void DeviceAdded (void* refCon, io_iterator_t iterator) { io_service_t service = 0; //叠代所有的匹配對象 while ((service = IOIteratorNext(iterator)) != 0) { CFStringRef className; io_name_t name; //列出所有的 IOUSBDevice 忽略IOUSBDevice子類的對象 className = IOObjectCopyClass(service); if (CFEqual(className, CFSTR("IOUSBDevice")) == true) { IORegistryEntryGetName(service, name); printf("Found device with name: %s\n", name); } CFRelease(className); IOObjectRelease(service); } } int main (int argc, const char * argv[]) { CFDictionaryRef matchingDict = NULL; io_iterator_t iter = 0; IONotificationPortRef notificationPort = NULL; CFRunLoopSourceRef runLoopSource; kern_return_t kr; //創建一個匹配字典,用於查找任意的 USB 設備 matchingDict = IOServiceMatching("IOUSBDevice"); notificationPort = IONotificationPortCreate(kIOMasterPortDefault); runLoopSource = IONotificationPortGetRunLoopSource(notificationPort); //RunLoop機制 CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode); //設置回調 kr = IOServiceAddMatchingNotification(notificationPort, kIOFirstMatchNotification, matchingDict, DeviceAdded, NULL, &iter); DeviceAdded(NULL, iter); CFRunLoopRun(); IONotificationPortDestroy(notificationPort); // IOObjectRelease(iter); return 0; }
Found device with name: Bluetooth USB Host Controller
Found device with name: BRCM20702 Hub
Found device with name: IOUSBHostDevice

實時叠代所有連接的 USB 硬件設備