Is there any way to run a script only at shutdown?
I mean, only when the computer is really shutting down to off state. This script should not run when doing just a log off or restart.
Is there any way to run a script only at shutdown?
I mean, only when the computer is really shutting down to off state. This script should not run when doing just a log off or restart.
Here is a way that does work (I just tested it) but it is quite technical and not for inexperienced people... I put a wrapper around /sbin/shutdown. This will work even if you shutdown your Mac from the Apple menu in the GUI.
Basically, you need to
su
to root, like this, and rename the existing, Apple-suppliedshutdown
binary toshutdown.orig
.Then you create a bash script called
shutdown
that does what you want first, thenexecs
the original Apple-supplied shutdown binary.There are three things to watch out for...
Be careful! And make a backup first!
Few days ago I published on github a configuration/script able to be executed at boot/shutdown.
Basically on Mac OS X you could/should use a
System wide and per-user daemon/agent configuration file
(plist) in conjunction with a bash script file. This is a sample of the plist file you could use:You can place this file into
/Library/LaunchDaemons
. There are many directories where the plist file could be placed, it depends from what you need, the rights of the process and so on.This script
boot-shutdown.sh
will be loaded and executed at every boot/shutdown.Then call
launchctl
command which load and unload daemons/agents.It looks like the most straightforward way would be to write a small C++ application that would run as a daemon with launchctl, catch the shutdown notification but ignore the reboot notification (see below) and then call whatever is given to it as arguments, e.g. a shell script. It does not look like Apple provides libraries to catch those notifications in any other language.
From the "Kernel Programming" manual https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/KernelProgramming/KernelProgramming.pdf from Apple, page 150:
"Although OS X does not have traditional BSD-style shutdown hooks, the I/O Kit provides equivalent functionality in recent versions. Since the I/O Kit provides this functionality, you must call it from C++ code."
"To register for notification, you call registerSleepWakeInterest (described in IOKit/RootDomain.h) and register for sleep notification. If the system is about to be shut down, your handler is called with the message type kIOMessageSystemWillPowerOff. If the system is about to reboot, your handler gets the message type kIOMessageSystemWillRestart. If the system is about to reboot, your handler gets the message type kIOMessageSystemWillSleep."
As you can see there is a different message for reboot, so you can handle the shutdown case exclusively.