tmpnam函数的C / C ++的线程安全? [英] C/C++ Thread-safety of tmpnam?

查看:294
本文介绍了tmpnam函数的C / C ++的线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用C ++中的使用tmpnam 的功能,但我需要知道它的线程安全。也就是说,如果我有多个线程,将每个需要为临时文件获得一个不同的名字,我是保证每个线程将收到一个文件使用不同的名称?

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?

推荐答案

使用tmpnam只保证文件不当时存在 - 但它可以被创建之前,你可以这样做你自己。为了安全地使用它,你总是需要再试图创建与打开文件(文件名,O_CREAT | O_EXCL | O_NOFOLLOW)。如果失败是由于EEXIST或ELOOP,回去尝试一个新的名称。

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.

这是特别重要的,以防止攻击符号链接,在另一个程序从临时文件名创建一个符号链接到/ etc / passwd文件或其他一些重要的文件。

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.

此外,还要确保你没有通过NULL来使用tmpnam,如则使用的缓冲区是所有线程是相同的。

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

结合这些另一方法是使用mkstemp()或mkostemp(),这将安全地创建该文件为您

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

最后,如果你不需要的文件名,你可以使用TMPFILE(),这将创建在接近被删除临时文件。

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

这篇关于tmpnam函数的C / C ++的线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆