fix file descriptor handling and clean up