It looks like this file descriptor can leak if some error occurs before the two calls to `close`. Maybe refactor it in terms of a transaction, i.e. with `scope(exit)` or similar?