How to create a file only if it doesn't exist?

前端 未结 5 1310
庸人自扰
庸人自扰 2021-01-12 04:10

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 identifie

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-12 04:48

    man 2 open:

    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.

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

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

提交回复
热议问题