获取有关Swift中进程的信息

时间:2017-05-09 16:10:43

标签: swift process usage-statistics

我正在尝试获取有关Swift中进程的一些数据。 我使用此代码作为起点:

pid_t pid = 10000;
rusage_info_current rusage;
if (proc_pid_rusage(pid, RUSAGE_INFO_CURRENT, (void **)&rusage) == 0)
{
    cout << rusage.ri_diskio_bytesread << endl;
    cout << rusage.ri_diskio_byteswritten << endl;
}

取自Per Process disk read/write statistics in Mac OS X

但是,我无法将上面的代码转换为Swift:

var usage = rusage_info_v3()     
if proc_pid_rusage(100, RUSAGE_INFO_CURRENT, &usage) == 0
{
    Swift.print("Success")
}

函数prod_pid_rusage需要一个类型为rusage_info_t?的参数,但是我无法实例化该类型的实例。 是否可以在Swift中使用该功能?

此致 的Sascha

1 个答案:

答案 0 :(得分:3)

与C一样,你必须取rusage_info_current的地址 变量并将其强制转换为proc_pid_rusage()期望的类型。 在Swift中,这是使用withUnsafeMutablePointer()完成的 和withMemoryRebound()

let pid = getpid()
var usage = rusage_info_current()

let result = withUnsafeMutablePointer(to: &usage) {
    $0.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) {
        proc_pid_rusage(pid, RUSAGE_INFO_CURRENT, $0)
    }
}
if result == 0 {
    print(usage.ri_diskio_bytesread)
    // ...
}

你必须添加

#include <libproc.h>

到桥接头文件以使其编译。