views:

173

answers:

1

I need to use the tmpnam function in C++, but I need to know about its thread safety. Namely, If I have several threads which will each need to acquire a different name for a temporary file, am I guaranteed that each thread will receive a file with a different name?

+4  A: 

tmpnam only guarantees that the file did not exist at the time - but it may be created before you can do so yourself. To use it safely, you will ALWAYS need to then attempt to create the file with open (filename, O_CREAT | O_EXCL | O_NOFOLLOW). If this fails due to EEXIST or ELOOP, go back and try a new name.

This is particularly important to protect against symlink attacks, where another program creates a symlink from your temp file name to /etc/passwd or some other important file.

Also, make sure you do not pass NULL to tmpnam, as the buffer used then is the same for all threads.

Another approach which combines these is to use mkstemp() or mkostemp(), which will create the file safely for you.

Finally, if you don't need the filename, you can use tmpfile(), which will create a temporary file that will be deleted on close.

bdonlan
but mkstemp is only for unix... :(
rlbond
what platform are you on?
bdonlan
need cross platform.
rlbond
Avoiding symlink traversal isn't possible in a portable way... you might just have to write one version for windows and one for *nix. Or use a secure random number generator to generate a long filename with a vanishingly small probability of collision.
bdonlan