Fix a race condition in output file handling