POSIX Alarm Timers in Python

One of the nifty new features in Linux 3.0 is the addition of two new POSIX clocks CLOCK_BOOTTIME_ALARM and CLOCK_REALTIME_ALARM. These clocks behave much like their non _ALARM versions, except they have the interesting property that they will set the alarm on your computer's RTC so that it will wake from suspend if used as a timer.

Pretty nifty if you want to write an alarm clock applet or want your machine to run some task at regular intervals and then go back to sleep.

Feeling adventitious I decided to try this out using Python since it seemed like a fun thing to do. Python has the wonderful ctypes module that allows you to load a shared object and access symbols defined inside. The only real downside with this approach is that, because of the way that most C libraries rely upon pre-processor defines and structures, you have to duplicate these definitions in your Python script. This gets particularly ugly if you start messing with opaque data structures like sigevent - basically you're ruining portability by tying yourself directly to a particular systems implementation of this interface (take a look at /usr/include/bits/siginfo.h). There's a few interesting solutions like ctypes_configure or writing a C wrapper library that avoids these headers, but I wanted to keep things simple (and see how well ctypes works on a complicated interface).

And here it is:

Usage is pretty simple - run this Python script, suspend your machine and after 1 minute your computer should magically wake itself up. Since the POSIX Alarm Timers require the CAP_WAKE_ALARM capability, you'll probably need to run this with sudo.

(In theory you should also be able to do something like `setcap cap_wake_alarm=ep alarmtimer.py` but the setcap program doesn't seem to recognise this capability yet).