问题
I can retrieve an OS X disk partition UUID by this code:
void PrintUUID()
{
DADiskRef disk;
CFDictionaryRef descDict;
DASessionRef session = DASessionCreate(NULL);
if (session) {
disk = DADiskCreateFromBSDName(NULL, session, "/dev/disk0s2");
if (disk) {
descDict = DADiskCopyDescription(disk);
if (descDict) {
CFTypeRef value = (CFTypeRef)CFDictionaryGetValue(descDict,
CFSTR("DAVolumeUUID"));
CFStringRef strValue = CFStringCreateWithFormat(NULL, NULL,
CFSTR("%@"), value);
print(strVal); <------------- here is the output
CFRelease(strValue);
CFRelease(descDict);
}
CFRelease(disk);
}
}
}
Above code retrieve UUID of disk0, I want to retrieve UUID of root disk (mount point = /), if I use "/" instead "/dev/disk0s2" then DADiskCopyDescription returns NULL. Also I know I can do it in Terminal by this command:
diskutil info /
Briefly how can I retrieve BSD Name of root disk? (to use it in DADiskCreateFromBSDName)
Anybody has an idea? Thanks.
回答1:
Use DADiskCreateFromVolumePath
instead of DADiskCreateFromBSDName
:
char *mountPoint = "/";
CFURLRef url = CFURLCreateFromFileSystemRepresentation(NULL, (const UInt8 *)mountPoint, strlen(mountPoint), TRUE);
disk = DADiskCreateFromVolumePath(NULL, session, url);
CFRelease(url);
Swift code:
let mountPoint = "/"
let url = URL(fileURLWithPath: mountPoint)
if let session = DASessionCreate(nil),
let disk = DADiskCreateFromVolumePath(nil, session, url as CFURL),
let desc = DADiskCopyDescription(disk) as? [String: CFTypeRef] {
if let uuid = desc["DAVolumeUUID"], CFGetTypeID(uuid) == CFUUIDGetTypeID() {
if let uuidString = CFUUIDCreateString(nil, (uuid as! CFUUID)) {
print(uuidString)
}
}
}
回答2:
DADiskCreateFromVolumePath is only included in OS 10.7 and above, so if you need to support older platforms like OS 10.4 and above (like me!) the only option is to use statfs to generate a BSD name from the posix name, so the entire function then becomes:
#include <sys/param.h>
#include <sys/mount.h>
void PrintUUID()
{
DADiskRef disk;
CFDictionaryRef descDict;
DASessionRef session = DASessionCreate (kCFAllocatorDefault);
if (session) {
struct statfs statFS;
statfs ("/", &statFS);
disk = DADiskCreateFromBSDName (kCFAllocatorDefault, session, statFS.f_mntfromname);
if (disk) {
descDict = DADiskCopyDescription (disk);
if (descDict) {
CFTypeRef value = (CFTypeRef) CFDictionaryGetValue (descDict, CFSTR("DAVolumeUUID"));
CFStringRef strValue = CFStringCreateWithFormat (NULL, NULL, CFSTR("%@"), value);
print (strValue) <------------- here is the output
CFRelease (strValue);
CFRelease (descDict);
}
CFRelease (disk);
}
CFRelease (session);
}
}
来源:https://stackoverflow.com/questions/17039361/how-to-programmatically-retrieve-uuid-of-root-disk-partition-in-os-x