列出Swift中带有参数的所有进程

koaltpgm  于 2023-01-19  发布在  Swift
关注(0)|答案(1)|浏览(123)

我试图将一些代码转换为Swift,列出所有运行的进程。但是由于它需要调用一些C特定的API,我有点挣扎。有人能告诉我这里我做错了什么吗?最后的print语句输出了不正确的值。我认为它应该是进程名称。还有行info = malloc(length)让我毛骨悚然。我应该如何正确地分配它?

var maxArgumentsSize: Int = 0
if maxArgumentsSize == 0 {
    var size: size_t = MemoryLayout<Int>.size
    var mib: [Int32] = [CTL_KERN, KERN_ARGMAX]
    let a = sysctl(&mib, 2, &maxArgumentsSize, &size, nil, 0)
    if a == -1 {
        maxArgumentsSize = 4096;
    }
}

var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_ALL]
var info: UnsafeMutableRawPointer? = nil
var length: size_t = 0
var count: Int = 0

if sysctl(&mib, 3, nil, &length, nil, 0) < 0 {
    exit(EXIT_FAILURE)
}

info = malloc(length)

if sysctl(&mib, 3, info, &length, nil, 0) < 0 {
    free(info)
    exit(EXIT_FAILURE)
}

count = length / MemoryLayout<kinfo_proc>.size
for index in 0...count {
    let info = info?.assumingMemoryBound(to: kinfo_proc.self)
    let pid: pid_t = info![index].kp_proc.p_pid
    let buffer = UnsafeMutablePointer<CChar>.allocate(capacity: maxArgumentsSize)
    var mib: [Int32] = [CTL_KERN, KERN_PROCARGS2, pid]
    if sysctl(&mib, 3, buffer, &maxArgumentsSize, nil, 0) == 0 {
        let str = String(cString: buffer, encoding: .utf8)
        print(str)
    }
    free(buffer);
}
mzmfm0qo

mzmfm0qo1#

基本上,我已经将我的初始代码更改为这样,并在最后调用@MartinR解决方案(https://stackoverflow.com/a/72445381/1187415)。当然,它不完整,直接从我的代码粘贴,但它的工作。

// Get all processess information:
var name: [CInt] = [CTL_KERN, KERN_PROC, KERN_PROC_ALL]
var length: size_t = 0
if sysctl(&name, CUnsignedInt(name.count), nil, &length, nil, 0) < 0 {
    return
}
var infoPtr = UnsafeMutableRawPointer.allocate(
    byteCount: length,
    alignment: MemoryLayout<kinfo_proc>.alignment
)
if sysctl(&name, CUnsignedInt(name.count), infoPtr, &length, nil, 0) < 0 {
    infoPtr.deallocate()
    return
}
let count = length / MemoryLayout<kinfo_proc>.size
for index in 0...count {
    let info = infoPtr.assumingMemoryBound(to: kinfo_proc.self)
    let pid: pid_t = info[index].kp_proc.p_pid
    let arguments = self.processArguments(pid: pid)
}
infoPtr.deallocate()

相关问题