Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
Wait for a stopped job's process to end before reading it again
Țugui Dragoș0072d61e4720
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swiftindex 0a762acb..d48e4d5c 100644--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift@@ -23,18 +23,38 @@ public enum BackgroundItemActions {item.canBeControlled ? nil : .launchctl(HelperRefusal.invalidRequest.rawValue)}+ /// How long Stop waits for the job's process to end, as long as `launchctl` itself gets.+ static let exitWait: TimeInterval = 30+@concurrentpublic static func stop(_ item: BackgroundItem) async throws(Failure) {+ try await stop(item, waitingUpTo: exitWait) { await Launchctl.run($0) }+ }++ /// Takes the job out of launchd, then waits up to `limit` for the process launchd still names for it to end:+ /// `bootout` returns at once, while launchd keeps a job whose process ignores the signal until its ExitTimeOut+ /// and only then kills it, and the job read meanwhile would still show as running.+ static func stop(+ _ item: BackgroundItem,+ waitingUpTo limit: TimeInterval,+ launchctl: ([String]) async -> (status: Int32, output: String)+ ) async throws(Failure) {if let refusal = refusal(for: item) { throw refusal }do throws(Failure) {if item.requiresPrivileges {try await runPrivileged(.bootout, for: item)} else {- try await run(["bootout", target(of: item)])+ try await run(["bootout", target(of: item)], with: launchctl)}} catch {- if !(await isGone(item)) { throw error }+ if !(await isGone(item, asking: launchctl)) { throw error }+ return}+ let printed = await launchctl(["print", target(of: item)])+ guard case .details(let details) = Launchctl.answer(status: printed.status, output: printed.output),+ let process = details.pid+ else { return }+ _ = await ProcessEnds.ends(process, within: limit)}/// How an item is started: loaded from its file with `bootstrap` when launchd does not have it, or@@ -174,12 +194,18 @@ public enum BackgroundItemActions {/// Whether launchd no longer has `item`: `launchctl print` exits with 113 for a job it does not have, in either/// domain and whoever asks. A job that went away by itself needed no stopping.- static func isGone(_ item: BackgroundItem) async -> Bool {- await Launchctl.run(["print", target(of: item)]).status == 113+ static func isGone(+ _ item: BackgroundItem,+ asking launchctl: ([String]) async -> (status: Int32, output: String) = { await Launchctl.run($0) }+ ) async -> Bool {+ await launchctl(["print", target(of: item)]).status == 113}- private static func run(_ arguments: [String]) async throws(Failure) {- let result = await Launchctl.run(arguments)+ private static func run(+ _ arguments: [String],+ with launchctl: ([String]) async -> (status: Int32, output: String) = { await Launchctl.run($0) }+ ) async throws(Failure) {+ let result = await launchctl(arguments)guard result.status == 0 else {throw .launchctl(Launchctl.withoutAdviceToRunAsRoot(result.output))}diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swiftindex 944aa772..0bc20634 100644--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift@@ -10,9 +10,9 @@ enum Launchctl {var pid: pid_t?}- /// Runs `launchctl` and returns its exit status and its output, error text included. `bootout` waits for- /// the job to exit, and a job that ignores the signal keeps it waiting for launchd's own time limit. A- /// removal waits on this call, so each call gets 30 seconds at most.+ /// Runs `launchctl` and returns its exit status and its output, error text included. `kickstart -k` waits for+ /// the job's process to exit and for launchd to start it again, which a job that ignores the signal, or one+ /// started moments before, makes take seconds. A removal waits on this call, so each call gets 30 seconds at most.@concurrentstatic func run(_ arguments: [String]) async -> (status: Int32, output: String) {switch await Subprocess.run("/bin/launchctl", arguments, timeout: 30) {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swiftindex 988b4ab3..053b4cd4 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift@@ -184,6 +184,36 @@ struct BackgroundItemActionsTests {#expect(item(state: .loaded, plist: file).offersEnableOrDisable)}+ @Test func stopWaitsForTheProcessLaunchdStillNamesToEnd() async throws {+ // `bootout` returns at once while launchd keeps a job that ignores the signal until its time runs out.+ let directory = try TemporaryDirectory()+ let program = try directory.runningProgram("job")+ let job = item(state: .running(pid: program.processIdentifier), plist: nil)+ let printed = """+ gui/501/com.example.agent = {+ \tpath = /Users/me/Library/LaunchAgents/com.example.agent.plist+ \tstate = SIGTERMed+ \tpid = \(program.processIdentifier)+ }+ """+ let asked = Mutex<[String]>([])+ let clock = ContinuousClock()+ Task {+ try? await Task.sleep(for: .milliseconds(300))+ program.terminate()+ }++ let started = clock.now+ try await BackgroundItemActions.stop(job, waitingUpTo: 5) { arguments in+ asked.withLock { $0.append(arguments[0]) }+ return arguments[0] == "print" ? (0, printed) : (0, "")+ }++ #expect(asked.withLock { $0 } == ["bootout", "print"])+ #expect(clock.now - started >= .milliseconds(250), "Stop returned while the process still ran")+ #expect(!program.isRunning)+ }+@Test func restartsOnlyAJobPeelMayControlAndAsksLaunchdToKillAndStartIt() async {var excluded = item(state: .running(pid: 42), plist: URL(filePath: "/Users/me/Library/LaunchAgents/job.plist"))excluded.isExcluded = truediff --git a/PeelHelper/HelperService.swift b/PeelHelper/HelperService.swiftindex 2e56654c..a2666e10 100644--- a/PeelHelper/HelperService.swift+++ b/PeelHelper/HelperService.swift@@ -178,7 +178,7 @@ final class HelperService: NSObject, PeelHelperProtocol {case .disable: ["disable", target]}- // 30 seconds: `bootout` waits for the job to exit, and the helper must never wait on `launchctl` forever.+ // 30 seconds: `kickstart -k` waits for the job to exit and start again, and the helper never waits forever.Task {switch await Subprocess.run("/bin/launchctl", arguments, timeout: 30) {case .success(let output): reply(output.status == 0 ? nil : output.text + output.errorText)