C 系统调用 open/read/write/close 和 O_CREAT|O_EXCL

标签 c system-calls

给定以下代码(应该在“helloworld”文件中写入“helloworld”,然后读取文本):

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

#define FNAME "helloworld"

int main(){ 
    int filedes, nbytes;
    char buf[128];

    /* Creates a file */
    if((filedes=open(FNAME, O_CREAT | O_EXCL | O_WRONLY | O_APPEND, 
        S_IRUSR | S_IWUSR)) == -1){
            write(2, "Error1\n", 7);
    }

    /* Writes hello world to file */
    if(write(filedes, FNAME, 10) != 10)
        write(2, "Error2\n", 7);

    /* Close file */
    close(filedes);

    if((filedes = open(FNAME, O_RDONLY))==-1)
        write(2, "Error3\n", 7);

    /* Prints file contents on screen */    
    if((nbytes=read(filedes, buf, 128)) == -1)
        write(2, "Error4\n", 7);

    if(write(1, buf, nbytes) != nbytes)
        write(2, "Error5\n", 7);

    /* Close file after read */
    close(filedes); 

    return (0);
}

我第一次运行这个程序,输出是:

helloworld

之后每次运行程序,输出都是:

Error1
Error2
helloworld

我不明白为什么没有附加文本,因为我已经指定了 O_APPEND 文件。 是因为我包含了 O_CREAT 吗? 如果文件已经创建,难道不应该忽略 O_CREAT 吗?

最佳答案

O_EXCL 强制创建文件。如果文件已经存在,则调用失败。

它用于确保必须创建文件,并在第三个参数中传递给定的权限。简而言之,您有以下选择:

  • O_CREAT:如果文件不存在,则创建具有给定权限的文件。如果文件存在,则打开它并忽略权限。
  • O_CREAT | O_EXCL:如果文件不存在,则创建具有给定权限的文件。如果文件存在,则失败。这对于创建锁定文件和保证对该文件的独占访问很有用(只要使用该文件的所有程序都遵循相同的协议(protocol))。
  • O_CREAT | O_TRUNC:如果文件不存在,则创建具有给定权限的文件。否则,将文件截断为零字节。当我们想到“创建一个新的空白文件”时,这会产生更多我们期望的效果。尽管如此,它仍然保留现有文件中已有的权限。

更多信息来自 the manual page :

O_EXCL

When used with O_CREAT, if the file already exists it is an error and the open() will fail. In this context, a symbolic link exists, regardless of where it points to. O_EXCL is broken on NFS file systems; programs which rely on it for performing locking tasks will contain a race condition. The solution for performing atomic file locking using a lockfile is to create a unique file on the same file system (e.g., incorporating hostname and pid), use link(2) to make a link to the lockfile. If link() returns 0, the lock is successful. Otherwise, use stat(2) on the unique file to check if its link count has increased to 2, in which case the lock is also successful.

关于C 系统调用 open/read/write/close 和 O_CREAT|O_EXCL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2572480/

相关文章:

c - C2HS 生成的 C 绑定(bind)中的链接器错误

c - 使用 BitBlt 捕捉桌面像素颜色

c - 如何通过kill命令从子进程向父进程发送信号

c - 系统调用不同的硬件架构?

c - 如何用 curl 做 keepalive http 请求?

c - 我将错误的数组长度传递给了函数。为什么我没有收到错误消息?

linux - 从 TID 获取 PID 的预制方法

c - C 中的指针在该算法中如何工作?

linux - Linux系统调用的多个命令