Files

28 lines
1.1 KiB
Swift

import Darwin
import Foundation
/// Collects the exit status of a child we signalled, so it does not linger as a zombie.
public enum ChildReaper {
/// Waits for `pid` without blocking a thread, sends SIGKILL once `grace` has passed, and returns once it is reaped.
///
/// Stops at once when `pid` is not an unreaped child of ours (someone else reaped it), so a
/// recycled pid is never signalled.
public static func reap(_ pid: pid_t, grace: TimeInterval = 2) async {
guard pid > 0 else { return }
let deadline = Date().addingTimeInterval(grace)
var killed = false
while true {
var status: Int32 = 0
let result = waitpid(pid, &status, WNOHANG)
if result == pid { return }
if result == -1 && errno != EINTR { return }
if result == 0 && !killed && Date() >= deadline {
kill(pid, SIGKILL)
killed = true
}
if Task.isCancelled { return }
try? await Task.sleep(nanoseconds: 20_000_000)
}
}
}