Handle SIGINT and SIGTERM, and clean up temp dirs on exit

This commit is contained in:
Greg Neagle
2024-09-07 16:51:21 -07:00
parent 45fd437eff
commit c4ae2bb6f9
2 changed files with 16 additions and 10 deletions
@@ -493,10 +493,7 @@ struct ManagedSoftwareUpdate: AsyncParsableCommand {
}
// MARK: main run function
mutating func run() async throws {
// TODO: implment signal handler for SIGTERM
if version {
print(getVersion())
return
@@ -514,6 +511,12 @@ struct ManagedSoftwareUpdate: AsyncParsableCommand {
doCleanupTasks(runType: runtype)
initializeReport()
// TODO: support logging to syslog and unified logging
// install handlers for SIGINT and SIGTERM
let sigintSrc = installSignalHandler(SIGINT)
sigintSrc.activate()
let sigtermSrc = installSignalHandler(SIGTERM)
sigtermSrc.activate()
munkiLog("### Starting managedsoftwareupdate run: \(runtype) ###")
if DisplayOptions.shared.verbose > 0 {
@@ -575,6 +578,7 @@ struct ManagedSoftwareUpdate: AsyncParsableCommand {
if !otherOptions.quiet {
print("Done.")
}
TempDir.shared.cleanUp()
if mustLogout {
// not handling this currently
+9 -7
View File
@@ -45,22 +45,24 @@ func installSignalHandler(_ sig: Int32) -> DispatchSourceSignal {
/// be sure to activate it!
// the intent here is to kill our child process(es) when we get a SIGINT or SIGTERM
// (sadly we can't do it for SIGKILL) so rsync doesn't keep running if we're stopped by
// the user
// (sadly we can't do it for SIGKILL) so they don't keep running if we're stopped
// by the user (or killed by another process)
signal(sig, SIG_IGN) // // Make sure the signal does not terminate the application.
let sigSrc = DispatchSource.makeSignalSource(signal: sig, queue: .main)
sigSrc.setEventHandler {
print("\nGot signal \(signalName(sig))")
munkiLog("Got signal \(signalName(sig))")
// kill all our child processes
let pid = ProcessInfo.processInfo.processIdentifier
for task in processesWithPPID(pid) {
print("Sending signal \(signalName(sig)) to \(task.command), pid \(task.pid)...")
let ourPid = ProcessInfo.processInfo.processIdentifier
for task in processesWithPPID(ourPid) {
munkiLog("Sending signal \(signalName(sig)) to \(task.command), pid \(task.pid)...")
kill(task.pid, sig)
}
// clean up our temp dirs
TempDir.shared.cleanUp()
// resend the signal to ourselves
signal(sig, SIG_DFL)
kill(pid, sig)
kill(ourPid, sig)
}
return sigSrc
}