Borrow some codes from libevent to make kqueue work fine