如何在cocoa应用程序中获取diskutil信息输出

hou*_*oft 4 macos cocoa disk objective-c

有没有办法以编程方式获得diskutil info / | grep "Free Space"给你的相同信息?(出于显而易见的原因,我宁愿有更好的方法来解决这个命令的结果.)

目前我正在使用statfs; 但是,我注意到这个报告的空间并不总是准确的,因为OS X还会在驱动器上放置临时文件,例如Time Machine快照.如果空间不足,这些文件将自动删除,操作系统不会报告这些文件的使用情况.换句话说,statfs通常提供比diskutil infoFinder中的磁盘信息更少的可用空间或查看磁盘信息.

Iva*_*hev 9

你可以使用popen(3):

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    FILE *f;
    char info[256];

    f = popen("/usr/sbin/diskutil info /", "r");
    if (f == NULL) {
        perror("Failed to run diskutil");
        exit(0);
    }

    while (fgets(info, sizeof(info), f) != NULL) {
        printf("%s", info);
    }

    pclose(f);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编辑

对不起,我没有仔细阅读这个问题.您还可以使用磁盘仲裁框架.还有一些可能有用的示例代码(FSMegaInfo).

UPDATE

我看了一下输出,otool -L $(which diskutil)似乎它正在使用一个名为的私有框架DiskManagement.framework.看了class-dump我看到的输出后,有一种volumeFreeSpaceForDisk:error:方法.所以尺寸从我得到了diskutil -info /FSMegaInfo FSGetVolumeInfo /我的工具有:

  • 磁盘工具: 427031642112 Bytes

  • 我的工具: volumeFreeSpaceForDisk: 427031642112

  • FSMegaInfo: freeBytes = 427031642112 (397 GB)

我还观察到大小不同(有几KB)每次我跑的工具之一,也是那个时候diskutil是1000分和FSMegaInfo由1024分,所以在GB大小将始终是不同的(相同的理由,与df -hdf -Hdiskutil - 基地10和基地2).

这是我的示例工具:

#import <Foundation/Foundation.h>
#import "DiskManagement.h"
#import <DiskArbitration/DADisk.h>

int main(int argc, char *argv[])
{
    int                 err;
    const char *        bsdName = "disk0s2";
    DASessionRef        session;
    DADiskRef           disk;
    CFDictionaryRef     descDict;
    session  = NULL;
    disk     = NULL;
    descDict = NULL;
    if (err == 0) {session = DASessionCreate(NULL); if (session == NULL) {err = EINVAL;}}
    if (err == 0) {disk = DADiskCreateFromBSDName(NULL, session, bsdName); if (disk == NULL) {err = EINVAL;}}
    if (err == 0) {descDict = DADiskCopyDescription(disk); if (descDict == NULL) {err = EINVAL;}}

    DMManager *dmMan = [DMManager sharedManager];
    NSLog(@"blockSizeForDisk: %@", [dmMan blockSizeForDisk:disk error:nil]);
    NSLog(@"totalSizeForDisk: %@", [dmMan totalSizeForDisk:disk error:nil]);
    NSLog(@"volumeTotalSizeForDisk: %@", [dmMan volumeTotalSizeForDisk:disk error:nil]);
    NSLog(@"volumeFreeSpaceForDisk: %@", [dmMan volumeFreeSpaceForDisk:disk error:nil]);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

您可以DiskManagement.h通过运行获取class-dump /System/Library/PrivateFrameworks/DiskManagement.framework/Versions/Current/DiskManagement > DiskManagement.h,您可以通过使用-F/System/Library/PrivateFrameworks/和添加私有框架路径来链接到该框架-framework.

编译:

clang -g tool.m -F/System/Library/PrivateFrameworks/ -framework Foundation -framework DiskArbitration -framework DiskManagement -o tool
Run Code Online (Sandbox Code Playgroud)

更新2: 你也可以看看这里这里.如果FSMegaInfo样品不为你工作,那么你可以stat/Volumes/.MobileBackups和减去它的大小由你得到了什么statfs("/", &stats).