temporary files - what is the resolution?

Marco Leise Marco.Leise at gmx.de
Fri Jul 27 08:29:37 PDT 2012


Am Wed, 25 Jul 2012 19:24:21 -0700
schrieb Jonathan M Davis <jmdavisProg at gmx.com>:

> […] As bad as tmpfile is, at least it _sort 
> of_ works. But it doesn't give you a file name, and it deletes the file when 
> it's closed, both which make it unusable for a lot of use cases.
> 
> I was working on a solution but ran into problems on Windows due to missing C 
> function declarations which were required in order to be able to create a 
> temporary file without introducing a race condition, and I temporarily tabled 
> it. I need to get back to it.
> 
> I did create a nice, cross-platform function for generating a random file name 
> which used D's random number generators and created a pull request for it ( 
> https://github.com/D-Programming-Language/phobos/pull/691 ). By default, It 
> puts the file in the directory returned by std.file.tempDir, but you can give it 
> a different directory if you want to.
> 
> But there's technically a race condition if you check for the file's existence 
> and then create it if it didn't exist (and generate a new name if it did, 
> check that one for existence, etc.).
> 
> […]
>
> I have a fully working implementation on Linux. I just need to sort out the 
> Windows C function declaration problem before I can create a pull request for 
> it. I expect that it'll be in 2.061.
> 
> - Jonathan M Davis

I've had to write something up myself, too. But with the closed bug in the Digital Mars C Runtime, I was wondering if there were actual operating system calls that cater for all our needs instead of writing our own functions. And that's where I stumbled upon the similarities between "GetTempFileName" on Windows and "mkstemp" on Posix. What makes me uneasy are the limits of the Windows API. A common wrapper around both would give us:

* free choice of base directory
* optional prefix string (only first 3 letters on Windows)
* can generate unique names (only up to 65,535 on Windows)
* avoids race conditions
* doesn't delete file after program termination

Actually I'd think mkstemp alone with it's random naming scheme and huge limits is what we want. It returns both the name and an open file descriptor with access for the current user only. In other words, my version(Posix) would be a one-liner ;). It's unfortunate that the Windows API doesn't offer something similarly secure and flexible.

Good luck with the race condition check on Windows!

-- 
Marco



More information about the Digitalmars-d mailing list