disknotificationd: watch for OSX disk attach/detach events and do something about them

downloads

overview

This tool will watch for DiskArbritration attach/detach events in MacOSX and when it sees them, do something. It was originally writtwen for a mate who wanted his laptop to back itself up automatically whenever he plugged in a certain USB hard drive. There are 2 active components:

First, disknotificationd. It's a stripped down version of Apple's DiskArbitration sample code, and expects to be called as disknotificationd /some/executable. It registers itself with DiskArbitration and whenever it sees a disk attached will call /some/executable appeared node with node set to the short device path for the full disk that's been attached and each partition on that disk. So if it's launched as

disknotificationd /usr/local/bin/my-backups.sh

and a disk with 2 partitions is plugged in, the following commands will be executed (perhaps with different disk IDs):

/usr/local/bin/my-backups.sh appeared disk1
/usr/local/bin/my-backups.sh appeared disk1s1
/usr/local/bin/my-backups.sh appeared disk1s2

When a disk remove is detected, the same happens but with disappeared as the first argument.

This is deliberately dead simple, on the assumption that the called executable will turn the device names into something meaningful to itself (perhaps by consulting the mount table, or whatever).

Second, the .plist file gets launchd to keep disknotificationd running in the background, doing it's thing, whenever you're logged in.

instructions

  1. place disknotificationd somewhere and make sure it's executable
    (eg. mkdir -p /usr/local/bin; mv ~/Desktop/disknotificationd /usr/local/bin; chmod +x /usr/local/bin/disknotificationd)
  2. make sure you've got a local LaunchAgents directory and put the .plist file there
    (eg. mkdir -p ~/Library/LaunchAgents/; mv ~/Desktop/org.slofith.disknotificationd.plist ~/Library/LaunchAgents/)
  3. edit the .plist file to make it do what you want - it will by default try to execute /usr/local/bin/my-backups.sh and send it's stdout/stderr to /tmp/disknotificationd.{out,err}

building

gcc disknotificationd.m -o disknotificationd -arch i386 -arch ppc -Wall -framework DiskArbitration -framework Foundation

contact

feedback? questions? russm at this domain is the easiest way to reach me.