获取有关 Swift 中进程的信息

ine*_*tus 4 process usage-statistics swift

我正在尝试获取有关 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;
}
Run Code Online (Sandbox Code Playgroud)

取自Mac OS X 中每进程磁盘读/写统计信息

但是,我在将上面的代码转换为 Swift 时遇到了麻烦:

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

函数 prod_pid_rusage 需要 rusage_info_t? 类型的参数,但我无法实例化该类型的实例。可以在 Swift 中使用该函数吗?

问候,萨沙

Mar*_*n R 5

与在 C 中一样,您必须获取rusage_info_current 变量的地址并将其转换为 所期望的类型proc_pid_rusage()。在 Swift 中,这是使用 withUnsafeMutablePointer() and完成的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)
    // ...
}
Run Code Online (Sandbox Code Playgroud)

你必须添加

#include <libproc.h>
Run Code Online (Sandbox Code Playgroud)

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