Monday, April 22, 2013

Keeping OS X Awake

Wake up and smell the coffee...

OS X 10.8 has quite an agressive sleep strategy. Quite often, when writing programs for the Enigmatic Code site, I need to stop my laptop sleeping while it runs a program to generate a solution to one of the problems.

I found out last year about the caffeinate command in OS X, which stops the system from sleeping while a command is running. So I often use something like this:
time caffeinate pypy enigma82.py 6

if I want to leave my laptop running something when I'm out, or overnight (and know how long it took).

But what happens if a program has been running for a while and you forgot caffeinate it before you started? You don't want to kill it off and lose all the work it's done, just so you can restart it under caffeinate.

Well the answer is simple, just write a quick Python¹ program to monitor the process you are interested in, and caffeinate that instead.

Here's my quick Python program - I called it pid-exists - it just monitors a process (using the pid specified as the command line argument), until it disappears, and then exits itself.
import sys
import os
import time

PID = int(sys.argv[1])

while True:
  try:
    os.kill(PID, 0)
  except OSError:
    break
  time.sleep(10)

Then you caffeinate that instead. For example:
caffeinate pid-exists 57905

will stop the laptop from sleeping while the process while pid 57905 is active. Once the process 57905 terminates then so will the pid-exists process and the parent caffeinate process and the laptop will go back to it's normal sleep strategy.

Note: On OS X 10.11 you can now just use:
caffeinate -w <pid>
to keep the computer awake while process <pid> is running.

───
¹ Other scripting languages are available.

No comments: