Search code examples
cmacossleep

Execute command just before Mac going to sleep


I wrote a C program/LaunchDaemon that checks if my MacBook is at home (connected to my WLAN). If so, it disables my password protection; if not, it enables it.

Easy. But the problem is that when I take my MacBook anywhere else and password protection is disabled, it will wake up without a password protection.

My fix for this would be: enable the password protection every time just before it goes to sleep.

QUESTION: is there any way find out when my Mac is preparing for sleep? Some interupt I can let my program listen to?


Solution

  • You can do it using I/O Kit, check Apple's QA1340: Registering and unregistering for sleep and wake notifications. You may also want to analyze the SleepWatcher utility sources or use/integrate for your needs. From the homepage:

    SleepWatcher 2.2 (running with Mac OS X 10.5 to 10.8, source code included) is a command line tool (daemon) for Mac OS X that monitors sleep, wakeup and idleness of a Mac. It can be used to execute a Unix command when the Mac or the display of the Mac goes to sleep mode or wakes up, after a given time without user interaction or when the user resumes activity after a break or when the power supply of a Mac notebook is attached or detached. It also can send the Mac to sleep mode or retrieve the time since last user activity. A little bit knowledge of the Unix command line is required to benefit from this software.