Running a Shell Script on Shutdown via launchd

你离开我真会死。 提交于 2019-12-06 11:49:54

@gaige thanks for the reply! In the end I went for the following:

#!/bin/sh
StartService() {
    echo "Started"
}

StopService() {
    echo "Stopped"
    exit 0
}

StartService
trap StopService SIGTERM
while true; do
    sleep 86400 &
    wait $!
done

Sleeping for a full day should prevent it from wasting any processing power, though it's not exactly my favourite solution to have something running like that. However, launchd doesn't really have any criteria that seemed like it would allow my script to only run at shutdown. The above instead is run on load (login) and then captures a SIGTERM on termination, logout or shutdown. Note the asynchronous use of sleep, as some environments will wait for the sleep to finish before executing the trap, which is no good as launchd only allows a couple of seconds to respond to SIGTERM before SIGKILL is sent.

As far as I can tell launchd only supports on demand services if they're triggered by a socket or watched path or whatever, which didn't really present a solution for me since it would still require some kind of outside influence.

One beneficial side effect however is that any results I obtained in StartService, such as file pointers etc., can be easily accessed by StopService since it's just in memory, no need for file saving. Just doesn't feel like the most elegant solution, but hey, if it works it's fine!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!