Prevent prevent file descriptor leak in ShrinkDebugFile()

Squashed version of #2528