/ R. Matthew Emerson / blog

Getting disk insertion/removal notifications

February 6, 2007

On Mac OS X, there is a daemon called diskarbitrationd that can notifiy interested clients of the appearance of disks and filesystems. Users talk to diskarbitrationd via the Disk Arbitration framework.

For some reason, the current developer documentation doesn’t have much to say about this framework. It therefore appears to be necessary to grovel through the headers to figure out how to use it. Fortunately, the headers are well-commented.

I was able to throw together a trivial program in about 15 or 20 minutes from first looking at DiskArbitration.h. Maybe this will help someone out there.

#include <stdio.h>
#include <DiskArbitration/DiskArbitration.h>

void hello_disk(DADiskRef disk, void *context)
{
    printf("disk %s appeared\n", DADiskGetBSDName(disk));
}

void goodbye_disk(DADiskRef disk, void *context)
{
    printf("disk %s disappeared\n", DADiskGetBSDName(disk));
}

main()
{
    DASessionRef session;

    session = DASessionCreate(kCFAllocatorDefault);

    DARegisterDiskAppearedCallback(session, NULL, hello_disk, NULL);
    DARegisterDiskDisappearedCallback(session, NULL, goodbye_disk, NULL);

    DASessionScheduleWithRunLoop(session,
        CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);

    CFRunLoopRun();

    CFRelease(session);
    exit(0);
}