import Darwin import Foundation import HelderServices import Testing /// Children spawned with `posix_spawn`, so nothing but the reaper ever waits on them. @Suite struct ChildReaperTests { private func spawn(_ arguments: [String]) throws -> pid_t { var pid: pid_t = 0 let argv: [UnsafeMutablePointer?] = arguments.map { strdup($0) } + [nil] defer { argv.forEach { free($0) } } let status = posix_spawn(&pid, arguments[0], nil, nil, argv, environ) guard status == 0 else { throw POSIXError(POSIXErrorCode(rawValue: status) ?? .EIO) } return pid } /// True while the pid names a process, zombies included. private func exists(_ pid: pid_t) -> Bool { kill(pid, 0) == 0 || errno == EPERM } @Test(.timeLimit(.minutes(1))) func aTerminatedChildIsReapedInsteadOfLeftAsAZombie() async throws { let pid = try spawn(["/bin/sleep", "30"]) kill(pid, SIGTERM) await ChildReaper.reap(pid, grace: 5) #expect(!exists(pid)) } @Test(.timeLimit(.minutes(1))) func aChildThatIgnoresSigtermIsKilledAfterTheGracePeriod() async throws { let pid = try spawn(["/bin/sh", "-c", "trap '' TERM; while :; do sleep 1; done"]) kill(pid, SIGTERM) let started = Date() await ChildReaper.reap(pid, grace: 0.3) #expect(!exists(pid)) #expect(Date().timeIntervalSince(started) < 10) } @Test func aPidThatIsNotOurChildIsLeftAlone() async throws { await ChildReaper.reap(1, grace: 0.1) #expect(exists(1)) } }