C/C++ Thread-safety of tmpnam?

丶灬走出姿态 提交于 2019-12-10 15:23:54

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/1145048/c-c-thread-safety-of-tmpnam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!