Repository Public
1import Darwin2import Foundation34/// Verified facts about child processes, read from the kernel via libproc — never inferred from5/// terminal output. Used for the working directory of shells that do not emit OSC 7 and for the6/// name of the foreground program.7public enum ProcessInspector {8 /// Current working directory of `pid`, or nil when the process is gone or inaccessible.9 public static func currentDirectory(pid: pid_t) -> String? {10 var info = proc_vnodepathinfo()11 let size = Int32(MemoryLayout<proc_vnodepathinfo>.size)12 guard proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0, &info, size) == size else { return nil }13 let path = withUnsafePointer(to: &info.pvi_cdir.vip_path) { ptr in14 ptr.withMemoryRebound(to: CChar.self, capacity: Int(MAXPATHLEN)) { String(cString: $0) }15 }16 return path.isEmpty ? nil : path17 }1819 /// Short name of a process (e.g. "vim"), or nil.20 public static func name(pid: pid_t) -> String? {21 var buffer = [CChar](repeating: 0, count: Int(MAXPATHLEN))22 let n = proc_name(pid, &buffer, UInt32(buffer.count))23 guard n > 0 else { return nil }24 return String(cString: buffer)25 }2627 /// Foreground process group leader of the PTY whose master is `fd`, or nil.28 public static func foregroundProcessGroup(masterFD fd: Int32) -> pid_t? {29 guard fd >= 0 else { return nil }30 let pgrp = tcgetpgrp(fd)31 return pgrp > 0 ? pgrp : nil32 }33}34