Port over fix to bug 2662 from master branch (leaking file descriptors)