Shammer's Philosophy

My private adversaria

Invoke some script when system shutdown on Mac OS X

What I would like to do

I found How can I use launchd to run logout script | Discussion | Jamf Nation, and the way posted at 10/30/15 7:05 PM by Bruienne sounds good. His idea is invoking some script as a LaunchAgent which uses trap command waiting SIGINT, SIGHUP and SIGTERM. The process launched by LaunchAgent when a user logs in wouldn't be finished unless a user send kill them intentionally or System Shutdown. If this script has a infinite loop, the end of this script is the same time when system would be shutdown or user logout. Using this way enables to invoke some scripts when system would be shutdown.

Script Skelton

onLogout() {
    # Insert whatever script you need to run at logout
    exit
}

echo "INFO - Watching ${HOME}" >> /var/log/org.my.log

trap 'onLogout' SIGINT SIGHUP SIGTERM

while true; do
    sleep 86400 &
    wait $!
done

plist file($HOME/Library/LaunchAgent/logout-watcher.plist)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
	<key>Label</key>
	<string>org.my.logoutwatcher</string>
	<key>ProgramArguments</key>
	<array>
		<string>/usr/local/myorg/logoutwatcher.sh</string>
	</array>
	<key>RunAtLoad</key>
	<true/>
  </dict>
</plist>