3

I am trying to get some data about a process in Swift. I am using this code as a starting point:

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;
}

taken from Per Process disk read/write statistics in Mac OS X.

However, I have trouble converting the code above to Swift:

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

The function prod_pid_rusage expects a parameter of type rusage_info_t?, but I can not instantiate an instance of that type. Is it possible to use the function in Swift?

Regards, Sascha

Community
  • 1
  • 1
inexcitus
  • 2,471
  • 2
  • 26
  • 41

1 Answers1

5

As in C you have to take the address of a rusage_info_current variable and cast it to the type expected by proc_pid_rusage(). In Swift this is done using 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)
    // ...
}

You have to add

#include <libproc.h>

to the bridging header file to make it compile.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382