我想在用户插入 USB 密钥、添加外部磁盘和安装磁盘映像时更新存储设备列表。IOKit 的 IOServiceAddInterestNotification 看起来像是可行的方法,但在 kIOMediaClass 中注册一般兴趣的明显用途只是为您提供卸载卷的通知,而且只是有时而已。

这样做的正确方法是什么?

有帮助吗?

解决方案

DiskArbitration.h 中的以下调用正是我想要的:

  • DARegisterDiskAppearedCallback
  • DARegisterDiskDisappearedCallback
  • DARegisterDiskDescriptionChangedCallback

这些涵盖插入、删除(甚至是不可安装的卷)
元数据更改事件。

附:不要忘记添加您的 DASession 到一个运行循环
否则您将不会收到任何回调。

其他提示

  

我想在用户插入USB密钥,添加外部磁盘和安装磁盘映像时更新存储设备列表。

我可以用这段代码给你两个中的两个,我想这不会需要更多的工作来给你第三个。

File:               USBNotificationExample.c

Description:        This sample demonstrates how to use IOKitLib and IOUSBLib to set up asynchronous
                    callbacks when a USB device is attached to or removed from the system.
                    It also shows how to associate arbitrary data with each device instance.

http: //opensource.apple.com/source/IOUSBFamily/IOUSBFamily-385.4.1/Examples/Another%20USB%20Notification%20Example/USBNotificationExample.c

我个人长时间使用(稍微修改过此代码的副本)来监控USB硬盘的连接。

从这个小样本中可以看出,它很容易证明适用于监控已安装的驱动器。或者它可能不会。 YMMV。

    matchingDict = IOServiceMatching(kIOUSBDeviceClassName);        // Interested in instances of class
                                                                    // IOUSBDevice and its subclasses

和匹配时

void DeviceAdded(void *refCon, io_iterator_t iterator)
{
    kern_return_t           kr;
    io_service_t            usbDevice;
    IOCFPlugInInterface     **plugInInterface=NULL;
    SInt32                  score;
    HRESULT                 res;    

    while ( (usbDevice = IOIteratorNext(iterator)) )
    {
        io_name_t                   deviceName;
        CFStringRef                 deviceNameAsCFString;
        MyPrivateData               *privateDataRef = NULL;
        UInt32                      locationID;

        printf("Device 0x%08x added.\n", usbDevice);

依此类推,等等。

观看 / Volumes 进行更改是否可以满足您的需求?

如果您恰好在 Cocoa 级别工作,您还可以注册以接收以下通知: NS工作区:

  • NSWorkspaceDidMountNotification
  • NSWorkspaceDidRenameVolumeNotification
  • NSWorkspaceWillUnmountNotification
  • NSWorkspaceDidUnmountNotification
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top