Files
networkcity/Sources/NetworkCityCore/ProcessNamer.swift
T

27 lines
927 B
Swift
Raw Normal View History

import Foundation
import Darwin
/// Resolves a pid to its real executable name via `proc_pidpath`, because
/// nettop's name column is unreliable (it reported `claude` as `2.1.177`).
/// Results are cached; drive from a single thread/actor.
public final class ProcessNamer {
private var cache: [Int32: String] = [:]
public init() {}
public func name(for pid: Int32) -> String? {
guard pid > 0 else { return nil }
if let hit = cache[pid] { return hit }
var buffer = [CChar](repeating: 0, count: 4096) // PROC_PIDPATHINFO_MAXSIZE
let length = proc_pidpath(pid, &buffer, UInt32(buffer.count))
guard length > 0 else { return nil }
let path = String(cString: buffer)
// `/Applications/Google Chrome.app/.../Google Chrome Helper` -> last component
let name = (path as NSString).lastPathComponent
cache[pid] = name
return name
}
}