Roughly ported to kqueue.