監聽設備移除
阿新 • • 發佈:2018-08-26
rem std iterator 狀態改變 xcod mod message eat mina
//
// main.c
// DriverIterator
//
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOMessage.h>
void DeviceNotification (void* refCon, io_service_t service, natural_t messageType, void* messageArgument);
//描述驅動程序實例的結構體
typedef struct {
io_service_t service;
io_object_t notification;
} MyDriverData;
//通知端口,用於設備接入和驅動程序狀態改變
IONotificationPortRef gNotificationPort = NULL;
//回調
void DeviceAdded (void* refCon, io_iterator_t iterator)
{
io_service_t service = 0;
// 叠代所有匹配對象
while ((service = IOIteratorNext(iterator)) != 0)
{
MyDriverData* myDriverData;
kern_return_t kr;
//分配一個結構體,保存驅動程序實例
myDriverData = (MyDriverData*)malloc(sizeof(MyDriverData));
//為該驅動程序實例保存 io_service_t
myDriverData->service = service;
// 安裝回調,接收驅動程序狀態改變通知
kr = IOServiceAddInterestNotification(gNotificationPort,
//驅動程序對象
service,
kIOGeneralInterest,
DeviceNotification, // 回調
myDriverData, // 傳遞給回調的refCon
&myDriverData->notification);
}
}
void DeviceNotification (void* refCon, io_service_t service, natural_t messageType, void* messageArgument)
{
MyDriverData* myDriverData = (MyDriverData*)refCon;
kern_return_t kr;
//只處理驅動程序終止通知
if (messageType == kIOMessageServiceIsTerminated)
{
//輸出移除設備的名稱
io_name_t name;
IORegistryEntryGetName(service, name);
printf("Device removed: %s\n", name);
//移除驅動程序狀態改變通知
kr = IOObjectRelease(myDriverData->notification);
//釋放驅動程序對象的引用
IOObjectRelease(myDriverData->service);
//釋放保存驅動程序連接的結構體
free(myDriverData);
}
}
int main (int argc, const char * argv[])
{
CFDictionaryRef matchingDict = NULL;
io_iterator_t iter = 0;
CFRunLoopSourceRef runLoopSource;
kern_return_t kr;
//創建一個匹配字典,用於查找任意的 USB 設備
matchingDict = IOServiceMatching("IOUSBDevice");
//創建一個端口
gNotificationPort = IONotificationPortCreate(kIOMasterPortDefault);
runLoopSource = IONotificationPortGetRunLoopSource(gNotificationPort);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
//註冊回調
kr = IOServiceAddMatchingNotification(gNotificationPort, kIOFirstMatchNotification, matchingDict, DeviceAdded, NULL, &iter);
DeviceAdded(NULL, iter);
CFRunLoopRun();
IONotificationPortDestroy(gNotificationPort);
IOObjectRelease(iter);
return 0;
}
liuhailong:~ liuhailong$ /Users/liuhailong/Library/Developer/Xcode/DerivedData/DriverIterator-czxxwkiooesdvlcbdaplulnfglcj/Build/Products/Debug/DriverIterator
Device removed: IOUSBHostDevice
監聽設備移除