Catching SIGTERM in daemon

I have a process that I start and keep alive like this.

ServerMain.shared.startFSM()
CFRunLoopRun()

Now I’m trying to react accordingly to when the computer is going to sleep, or shutting down so I’m trying to catch the SIGTERM signal as follows.

  private func setSIGTERMSignalHandler() {
        let signalSource = DispatchSource.makeSignalSource(signal: SIGTERM, queue: .main)
        signalSource.setEventHandler {
            self.signOut()
        }
        signalSource.resume()
        signTermSource = signalSource
    }

However the event handler is not getting called in any circumstance. Is this the right track to catch them since it is a LaunchDaemon?

Answered by DTS Engineer in 795951022

You’ll see different SIGTERM behaviour depending on how your daemon is set up:

  • If your daemon has transactions enabled and there are no outstanding transactions, you won’t get a SIGTERM. In that case launchd assumes that your daemon is ‘clean’ and kill it immediately using SIGKILL.

  • If not, your daemon will get a SIGTERM but, if you doesn’t terminate quickly enough, launchd will then kill it with SIGKILL.

The launchd.plist man page has more details on this.

When it comes to the restart and shutdown case specifically, launchd is particularly agressive about this.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Thank you for the links.

Accepted Answer

I was unable to catch any signals but I ended up using the “PowerManagement” library, which allow to get notifications when system is going sleep, waking up.

You’ll see different SIGTERM behaviour depending on how your daemon is set up:

  • If your daemon has transactions enabled and there are no outstanding transactions, you won’t get a SIGTERM. In that case launchd assumes that your daemon is ‘clean’ and kill it immediately using SIGKILL.

  • If not, your daemon will get a SIGTERM but, if you doesn’t terminate quickly enough, launchd will then kill it with SIGKILL.

The launchd.plist man page has more details on this.

When it comes to the restart and shutdown case specifically, launchd is particularly agressive about this.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Catching SIGTERM in daemon
 
 
Q