clean up file descriptor leak and check for io before thread cancellation