C / C ++ Thread Security tmpnam?

I need to use the tmpnam function in C ++, but I need to know its thread safety. Namely: if I have several streams, each of which will have to get a different name for the temporary file, can I guarantee that each stream will receive a file with a different name?

+4
source share
1 answer

tmpnam ensures that the file did not exist at that time, but it can be created before you can do it yourself. To use it safely, you should ALWAYS try to create a file that is open (file name, O_CREAT | O_EXCL | O_NOFOLLOW). If this fails due to EEXIST or ELOOP, go back and try a new name.

This is especially important for protection against symlink attacks, where another program creates a symbolic link from your temp file name to the / etc / passwd file or some other important file.

Also, make sure that you do not pass NULL to tmpnam, since the buffer used is the same for all streams.

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

Finally, if you do not need a file name, you can use tmpfile (), which will create a temporary file that will be deleted when it is closed.

+5
source

All Articles