Similar to this question, I'd like to limit the execution time of a function--preferably with microsecond accuracy--in C. I imagine that C++ exceptions could be used to achieve a result similar to this Python solution. Though it's not ideal, such an approach is wholly unavailable in plain C.
I wonder, then, how might I interrupt the execution of a function after a certain time interval in C on a Posix system? For relatively simple situations a bit of silly business works just fine, but that adds a fair amount of code orthogonal to the problem solution. Let's say I have a function like so:
void boil(egg *e) {
while (true)
do_boil(e);
}
I want to run run boil on an egg*, interrupting it every 50μs to check do something like so:
egg *e = init_egg();
while (true) {
preempt_in(50, (void) (*boil), 1, e);
/* Now boil(e) is executed for 50μs,
then control flow is returned to the
statement prior to the call to preempt_in.
*/
if (e->cooked_val > 100)
break;
}
I realize that pthreads could be used to do this, but I'm rather more interested in avoiding their use. I could switch between ucontext_t's in a SIGALRM handler, but the POSIX standard notes that the use of setcontext/swapcontext is not to be used in a signal handler and, indeed, I note differing behaviors between Linux and Solaris systems when doing so.
Is this effect possible to achieve? If so, in a portable manner?