There are a couple of tools that allow you to intercept OS X' power status changes:
- Scenario and Power Manager, both commercial and GUI tools.
- Sleep Watcher, free and open source, but command line.
Sleep Watcher installation
Let's try this with Sleep Watcher. Download the tool from Bernhard Baehr's homepage and follow the installation instructions: assuming you unpacked the download to your Desktop, call the following commands from a Terminal window:
sudo mkdir -p /usr/local/sbin /usr/local/share/man/man8 sudo cp ~/Desktop/sleepwatcher_2.2/sleepwatcher /usr/local/sbin sudo cp ~/Desktop/sleepwatcher_2.2/sleepwatcher.8 /usr/local/share/man/man8
This will install the sleepwatcher
binary and the manpages. You will be prompted for an administrator password.
Creating a sleep script
Now, let's create a sleep script called ~/.sleep
. It will contain the commands that are run when the machine is put to sleep (i.e. when the lid closes).
touch ~/.sleep open -e !$
In this file, add the following:
osascript -e 'tell application "Remote Desktop Connection" to quit'
This will quit the Microsoft RDP application through AppleScript commands. You can do this with any application as long as you change the name according to its title. Save the file. Now we need to make it executable:
chmod +x ~/.sleep
Testing the sleep script
Now test your script by first starting the RDP program, then running the following in Terminal:
/usr/local/sbin/sleepwatcher --verbose --sleep ~/.sleep
This will not output anything, so leave both RDP and the Sleep Watcher running, then close the lid of your MacBook. Wait a couple of seconds until it really goes to sleep. Then wake it up again. Did RDP close? Great! Did something go wrong? Look at the output of the sleepwatcher
command to get a hint about where it failed.
You can now cancel the Sleep Watcher by pressing CtrlC in Terminal.
Running the script in background
In order to have the Sleep Watcher run at all times, you need to make it a LaunchDaemon. Create a new configuration file by copying the example configuration and rc
-scripts.
sudo cp ~/Desktop/sleepwatcher_2.2/config/de.bernhard-baehr.sleepwatcher-20compatibility.plist /Library/LaunchDaemons/de.bernhard-baehr.sleepwatcher.plist sudo cp ~/Desktop/sleepwatcher_2.2/config/rc.* /etc
Now load the configuration files with launchd
:
sudo launchctl load /Library/LaunchDaemons/de.bernhard-baehr.sleepwatcher.plist
That's all you need. Now the .sleep
file will always be executed whenever you sleep your Mac.