title: Recommended patterns for writing asynchronous evented servers in C
body: <p>I am writing my first single-threaded, single-process server in C using kqueue() / epoll() to handle asynchronous event dispatch. As one would expect, it is quite a lot harder to follow the flow of control than in a blocking server.</p>
  
  <p>Is there a common pattern (maybe even with a name) that people use to avoid the callback-driven protocol implementation becoming a gigantic tangled hairball?</p>
  
  <p>Alternately, are there any nonblocking servers written in C for which the source code is a pleasure to read?</p>
  
  <p>Any input would be much appreciated!</p>
  
  <p>More thoughts:</p>
  
  <p>A lot of the cruft seems to come from the need to deal with the buffering of IO. There is no necessary correspondence between a buffer filling/draining and a single state transition. A buffer fill/drain might correspond to [0, N] state transitions.)</p>
  
  <p>I've looked at libev (<a href="http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod" rel="nofollow">docs here</a>) and it looks like a great tool, and libevent, which looks less exciting but still useful, but neither of them really answers the question: how do I manage the flow of control in a way that isn't horrendously opaque.</p>