-->

Temporary files & folders on Windows

2019-09-09 12:13发布

问题:

Emulating multithreading by loading a DLL multiple times (it's designed for this). Since LoadLibrary() doesn't really allow it, the DLL copies itself into a temporary file, via GetTempPath() and GetTempFileName().

It's a small file and upon thread destruction it frees the library and deletes the temporary file. Problem now is that the number of threads is configurable (maniacs can pick 50, 100, more) which basically exposes the risk of running unstable, crash and not go through the usual "delete temporary files" routine.

Is it okay if I just leave those temporary files to die there? Does the OS usually clean the up by itself? Or should I write an autocleanup routine? If yes, how can I go about saving another temporary file to hold a list with those files, and not hit UAC restrictions or otherwise?

Any ideas?

回答1:

Your LoadLibrary/multithreaded discussion leaves me confused, but that's ok.

Temp files on Windows don't generally get deleted by anything other than the process that created them. If the user runs the "Disk Cleanup" util or similar tool, he might be able to get those files automatically deleted for him. I don't think that happens too often.

Best approach. Have your application create a sub-directory within the temp folder (and possibly subfolders for each process instance). When you application exits, it cleans up it's own set of temp files via DeleteFile. On app re-start it can have some logic to cleanup folders and files still lingering around as a result of a previous process crashing.

You could also look at using the FILE_ATTRIBUTE_TEMPORARY flag on CreateFile.

You could also consider having a global exception handler for your process. The handler would delete it's own temp directory before exiting on a crash.



回答2:

Can you use FILE_FLAG_DELETE_ON_CLOSE parameter to CreateFile?