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?
views:
173answers:
1tmpnam 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.