From this answerThere does not seem to Possible to run scripts on sleep and wake?, the bestbe a way seemsfor a program to get notified when the lid is closed. However, the state of the lid can be to use a third party app - Scenario (paid) or SleepWatchermonitored periodically (freeand in this particular case, every second) and actions taken based on the lid state.
Caveats about sleep actions fromI do not know of any program that can provide a complete solution for your need, but you can use the Scenario programming guide:following information to build a solution yourself.
###Sleep Scripts
Sleep Scripts are launched right before the computer goes to sleep. Again, there are some important caveats with this type of script.
Download this clamshellstate.pl perl script
You can run it in Terminal
(under /Applications/Utilities
) like:
./clamshellstate.pl 1
When your computer goes to sleep, each program gets asked if it is ok to go to sleep and if not, the program gets a few seconds before they are forced to sleep. This way, no program can stop the computer from going to sleep and thus drain the battery and possibly create data loss.
to get an output like "Open" or "Closed" indicating the current lid state
The way Scenario deals with Sleep scripts is that it does not reply when the system asks it to sleep until all the scripts return that they are ready. This means your scripts must return a special error code the same way Log-out scripts do.
Create a shell script like (substitute script-to-run with a shell script you'd like to run):
./clamshellstate.pl 1 | grep Closed > /dev/null && *script-to-run*
Configure this script to run once every second using launchd.plist. Or use Lingon to easily configure launchd.plist.
If Scenario does not reply to the System that it is ready, the System will put the computer to sleep anyway. This happens after a few seconds (about 15). So whether your script replies that it is done or not, the computer will go to sleep anyway.
Note: Instead of clamshellstate.pl, you can also use the following command in Terminal
:
The difference between Sleep scripts and Log-out scripts is that Log-out scripts can cancel Log-out altogether, but Sleep scripts can only delay sleep from happening. This means that if your script takes too much time to run, it will be interrupted and the computer will go to sleep.
ioreg -r -k AppleClamshellState | grep '"AppleClamshellState" = Yes' | cut -f2 -d"="
This also means that if your script does not reply when it is done, your computer will wait until the default time out happens (15 seconds) which will add an unnecessary delay before Sleep occurs.
to get a "Yes" for the closed state and a "No" for the open state.