Monday, July 13, 2009

When the alarm clock goes of unexpectedly.

Recently, I saw someone questioning the need for an alarm 0; after code like

eval { alarm 5; do_stuff(); alarm 0;};

You don't need it under the two obvious code paths (code runs successfully within the time limit and code doesn't finish before the time limit), but if do_stuff(); dies, then you need to disable the alarm (because the alarm 0; in the block eval won't get a chance to run). My solution to this problem is

This function takes between two and four arguments. The first two are the number of seconds to wait before timing out and a reference to the code to run respectively. The next argument is a reference to code that should be run in the event that the code times out, and the last is a reference to code that should be run in the event that an error occurs. Here are a few examples of how to call it: