仅当文件不存在时才如何创建文件? [英] How to create a file only if it doesn't exist?

查看:68
本文介绍了仅当文件不存在时才如何创建文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个UNIX守护程序(以Debian为目标,但这无关紧要),我想提供一种创建".pid"文件(包含该守护程序的进程标识符的文件)的方法.

I wrote a UNIX daemon (targeting Debian, but it shouldn't matter) and I wanted to provide some way of creating a ".pid" file, (a file which contains the process identifier of the daemon).

我搜索了一种打开文件的方法,该方法仅在不存在但找不到文件的情况下.

I searched for a way of opening a file only if it doesn't exist, but couldn't find one.

基本上,我可以做类似的事情:

Basically, I could do something like:

if (fileexists())
{
  //fail...
}
else
{
  //create it with fopen() or similar
}

但是,就目前情况而言,此代码不会以原子方式执行任务,因此这样做很危险,因为在我的测试和创建过程中,可能会有另一个进程创建文件.

But as it stands, this code does not perform the task in a atomic fashion, and doing so would be dangerous, because another process might create the file during my test, and the file creation.

你们对如何做到有任何想法吗?

Do you guys have any idea on how to do that?

谢谢.

P.S:仅涉及std::streams的解决方案的加分点.

P.S: Bonus point for a solution which only involves std::streams.

推荐答案

man 2 open:

man 2 open:

O_EXCL确保此调用创建文件:如果此标志与O_CREAT一起指定,并且路径名已存在,则open() 将失败.如果未指定O_CREAT,则O_EXCL的行为是不确定的.

O_EXCL Ensure that this call creates the file: if this flag is specified in conjunction with O_CREAT, and pathname already exists, then open() will fail. The behavior of O_EXCL is undefined if O_CREAT is not specified.

因此,您可以调用fd = open(name, O_CREAT | O_EXCL, 0644);/* Open()是原子的. (出于某种原因)*/

so, you could call fd = open(name, O_CREAT | O_EXCL, 0644); /* Open() is atomic. (for a reason) */

更新:您当然应该将O_RDONLY,O_WRONLY或O_RDWR标志之一或添加到flags参数中.

UPDATE: and you should of course OR one of the O_RDONLY, O_WRONLY, or O_RDWR flags into the flags argument.

这篇关于仅当文件不存在时才如何创建文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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