Improve robustness of tmp file management