Timeboxing is a time management technique. Some humans find it beneficial to start with a fixed time period and size their work to fit. Can machines practice timeboxing too? Sure! That's kind of what an RTOS does. If you want to timebox a regular old unix program though, you'll need something else...
See how many files can be counted under your home directory in 5-6 seconds:
time timebox 5.0 1.0 find ~ | wc -l
The two numbers 5.0
and 1.0
are the run period and grace period, respectively. If the program doesn't exit before 5 seconds is up, timebox
sends it SIGTERM
. If it still hasn't exited after 6 seconds, timebox
sends it SIGKILL
. This is not unlike what init
does with running processes at shutdown.
-
Problems that have "best effort" solutions, like search. Exhaustive searches can take a long time. Perhaps you always want to respond with something within a second. In your search program, print the best result you've found so far when you receive
SIGTERM
. You can then run it undertimebox
. -
Suppose you're a cost-constrained cloud user being charged for cpu time. (I mean, who isn't these days?) You want to
crack a hashsolve a problem, but can't spend more than $X, even if that means you might not get a solution at all. Timebox it! -
College programming assignments where you a submit source code solution. A grading program compiles, runs, and checks the ouput of your program. But what if your program is naughty and never exits? Or what if you submit a small C++ program which generates GBs of compiler errors that take forever to format and print? Timebox it!
-
You want to expose a server, but only for a limited, short period of time. Forgetting and leaving it open indefinitely would be risky. Timebox it!
This was inspired by "Unix System Call Timeouts". Specifically, the "waitpid equivalent with timeout?" question on Stack Overflow. There are all kinds of ways to do this...
Set an alarm
and wait for SIGALRM
. This is hard to get right, and you need to watch out for race conditions.
Turn SIGCHLD
into a selectable event via signalfd
. Only works on Linux.
Use djb's self-pipe trick to turn SIGCHLD
into a selectable event. This is sort of the poor man's signalfd
, and is probably the most reliable and broadly portable way to do it. Although I wonder if the "can't safely mix select with signals" reason still applies on modern unixes.
Use sigtimedwait
with a signal set of SIGCHLD
. This is a nice, simple approach, but wouldn't mix well with an event loop doing other things. Not that we're doing that here, but it might be relevant in your program.
timebox
uses yet another way: wait for EOF
on a child-to-parent pipe, which happens when the pipe's write side is closed at child exit.