0

The question says it all. How can I get the block device from an NSURL representing, for example, a removable media? What I would like to get from /Volumes/MyDevice is something like /dev/disk2. I wonder if that is possible without using the IOKit framework! Any help is appreciated.

Nickkk
  • 2,261
  • 1
  • 25
  • 34

1 Answers1

2

DiskArbitration.framework will get you there:

NSURL *volumeURL = [NSURL fileURLWithPath:@"/Volumes/YourDisk"];

DASessionRef session = DASessionCreate(kCFAllocatorDefault);
DADiskRef disk = DADiskCreateFromVolumePath(kCFAllocatorDefault,
                                            session,
                                            (__bridge CFURLRef)volumeURL);

NSDictionary *desc = CFBridgingRelease(DADiskCopyDescription(disk));

/* See DADisk.h for a list of available keys */
NSLog(@"%@", desc[(NSString *)kDADiskDescriptionMediaBSDNameKey]);

CFRelease(disk);
CFRelease(session);

As will statfs(2):

struct statfs s;
statfs([[volumeURL path] fileSystemRepresentation], &s);
printf("%s\n", s.f_mntfromname);
jatoben
  • 3,079
  • 15
  • 12
  • Reading the description of `f_mntfromname` in the manpage, it didn't sound like what the questioner wanted, but I tried it and it is, indeed, a device path. The DiskArb code returns something *slightly* different: it's not the full `/dev/disk4` path, just the name, `disk4`. – Peter Hosey Apr 26 '13 at 20:34
  • Ah, yeah that's true. I've hardcoded the /dev prefix in some of my code -- given that its been around forever (and DiskManagement.framework seems to do so too), I thought it was safe enough. And I agree that `f_mntfromname` is confusingly documented. – jatoben Apr 26 '13 at 21:13
  • DiskArb was introduced in 10.3, IIRC, as a Private Framework; going by the documentation, it was made public in 10.4. – Peter Hosey Apr 26 '13 at 21:23
  • Thank you very much for your exhaustive answer. I decided to use `statfs` to get the block device as the DA framework returns only something like `disks1` to me. On the contrary, I have to use `DADiskUnmount` because `unmount(s.f_mntfromname,MNT_FORCE)` seems always to fail. – Nickkk Apr 27 '13 at 00:17
  • @Nickkk: `umount` (there is only one n) takes the path to the mount point, not the point to the device. – Peter Hosey Apr 27 '13 at 03:44
  • I tried `unmount(s.f_mntonname,MNT_FORCE)` and `unmount("/Volumes/UNTITLED",MNT_FORCE)` but neither worked. If I write `umount` instead of `unmount` I get a compiler error, and on the help page you get that the counterpart of `mount` is `unmount`: http://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/mount.2.html – Nickkk Apr 27 '13 at 10:51