1

I tried this code to get result from proc_pid_rusage:

import Foundation

let p1 = UnsafeMutablePointer<rusage_info_t?>.allocate(capacity: 1)

let spid = ProcessInfo.processInfo.processIdentifier
let status = proc_pid_rusage(spid, 0, p1)
if status == KERN_SUCCESS {
    // ...
    let umrp : rusage_info_t = p1.pointee!
    let a = umrp.load(as:rusage_info_v0.self)
    print("User time \(a.ri_user_time)")
}

print("Status \(status)")

rusage_info_t, as Xcode says, is defined as:

public typealias rusage_info_t = UnsafeMutableRawPointer

I assume that it should point to a struct rusage_info_v0 as I specified flavor = 0. But I get this runtime error:

Swift/UnsafeRawPointer.swift:1203: Fatal error: load from misaligned raw pointer
Trace/BPT trap: 5

I don't understand what alignment should be and how should I specify that.

egor10_4
  • 331
  • 2
  • 9
  • How about `umrp.loadUnaligned`? – Sweeper Apr 17 '23 at 13:58
  • 1
    Does this answer your question? https://stackoverflow.com/a/43876992/3141234 Most of the `proc` APIs take pointers to where they should store the result. You usually don't want to allocate new heap memory to point to. INstead, make a local variable of the correct type, and pass a pointer to that local variable with `&`. The proc API will fill it in for you, no heap allocation required – Alexander Apr 17 '23 at 15:10
  • `loadUnaligned` throws a segmentation fault. – egor10_4 Apr 17 '23 at 15:51
  • Thanks, Alexander. That helped me to get the result. I wonder if I can do the same with the heap allocated memory? – egor10_4 Apr 17 '23 at 15:59
  • @egor10_4 You can, but why? (By the way, people don't get notified of comments to others' posts unless you mentioned them) – Alexander Apr 17 '23 at 17:09

0 Answers0