//
//  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