Properly clean up closed fds in script recording