Run script before restart/shutdown Is it possible to execute a script/command right before OS X is shutting down or restarting?

I'd like to run sudo apachectl stop to stop apache from auto-starting.
You can use a logout hook:

sudo defaults write com.apple.loginwindow LogoutHook ~/.logouthook
echo $'#!/bin/bash\napachectl stop' &gt; ~/.logouthook
chmod +x ~/.logouthook


The value of the LogoutHook key can only be a path to an executable and not a shell command. The logout hook is run with superuser privileges so you don't need sudo.

The defaults command modifies /var/root/Library/Preferences/com.apple.loginwindow.plist. Adding a LogoutHook key to /Library/Preferences/com.apple.loginwindow.plist doesn't work.

If a logout hook takes long enough to run, a gray screen is shown until the logout hook terminates. There doesn't seem to be any time limit after which logout hooks are forced to terminate.

Logout hooks were deprecated in 10.4, but I haven't figured out any way to run programs on logout reliably with launchd. I haven't gotten rc.local.shutdown to work either. I don't know any way to run a logout hook before shutting down or restarting but not before logging out.