title: How to limit the execution time of a function in C/POSIX?
body: <p>Similar to this <a href="https://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python">question</a>, 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 <a href="https://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python/366763#366763">this</a> Python solution. Though it's not ideal, such an approach is wholly unavailable in plain C.</p>
  
  <p>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 <a href="http://troutwine.us/blog/telling_time.html" rel="nofollow noreferrer">silly business</a> 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:</p>
  
  <pre>
  <code>void boil(egg *e) {
      while (true)
      do_boil(e);
  }
  </code></pre>
  
  <p>I want to run run boil on an egg*, interrupting it every 50μs to check do something like so:</p>
  
  <pre>
  <code>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;
  }
  </code></pre>
  
  <p>I realize that pthreads could be used to do this, but I'm rather more interested in avoiding their use. I <em>could</em> 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.</p>
  
  <p>Is this effect <em>possible</em> to achieve? If so, in a portable manner?</p>