Question

I want to update a list of storage devices as the user inserts USB keys, adds external disks and mounts disk images. IOKit's IOServiceAddInterestNotification looks like the way to go, but the obvious use of registering general interest in kIOMediaClass only gives you notifications for unmounting of volumes and then only sometimes.

What's the right way to do this?

Was it helpful?

Solution

The following calls in DiskArbitration.h do exactly what I want:

  • DARegisterDiskAppearedCallback
  • DARegisterDiskDisappearedCallback
  • DARegisterDiskDescriptionChangedCallback

These cover insertion, removal (even of unmountable volumes)
metadata change events.

P.S. Don't forget to add your DASession to a runloop
or you won't get any callbacks.

OTHER TIPS

I want to update a list of storage devices as the user inserts USB keys, adds external disks and mounts disk images.

I can get you two out of three with this piece of code, which I imagine wouldn't require a lot more work to give you the third.

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

I've personally used (a slightly modified copy of this code) for a long time, to monitor the connection of USB HDDs.

As you can see from this small sample, it may easily prove adaptable to monitor mounted drives. Or it may not. YMMV.

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

and when it matches

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);

and so forth, and so on.

Would watching /Volumes for changes do what you need?

If you happen to be working at the Cocoa level, you can also register to receive the following notifications from NSWorkspace:

  • NSWorkspaceDidMountNotification
  • NSWorkspaceDidRenameVolumeNotification
  • NSWorkspaceWillUnmountNotification
  • NSWorkspaceDidUnmountNotification
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top