fdopen()会修改open()设置的文件权限吗?

huangapple go评论58阅读模式
英文:

why does fdopen() modify the file permissions set by open()

问题

I am using a simple C program where I am setting the file permissions while creating the file to 0664 with open() and then passing the file descriptor to fdopen() and doing fwrite() into the file followed by fclose(). But to my surprise, I see the file permissions change to 0644 after the program completes the execution.

My code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
    
int main (void)
{
    int fd = -1;
    FILE *fp = NULL;

    fd = open("/tmp/myfile.cfg", O_WRONLY | O_CREAT | O_CLOEXEC, 0664);
    fp = fdopen(fd, "w");
    fclose(fp);
    return 0;
}

Why do the file permissions get modified after the fd is handed over to fdopen()? How can I preserve the permissions that I set in the open() call?

英文:

I am using a simple C program where I am setting the file permissions while creating the file to 0664 with open() and then passing the file descriptor to fdopen() and doing fwrite() into the file followed by fclose(). But to my surprise, I see the file permissions change to 0644 after the program completes the execution.

My code:

#include&lt;stdio.h&gt;
#include&lt;stdlib.h&gt;
#include&lt;string.h&gt;
#include&lt;unistd.h&gt;
#include&lt;fcntl.h&gt;


int main (void)
{
    int fd = -1;
    FILE *fp = NULL;

    fd = open(&quot;/tmp/myfile.cfg&quot;, O_WRONLY | O_CREAT | O_CLOEXEC, 0664);
    fp = fdopen(fd, &quot;w&quot;);
    fclose(fp);
    return 0;
}

Why do the file permissions get modified after the fd is handed over to fdopen()? How can I preserve the permissions that I set in the open() call?

答案1

得分: 6

文件模式设置为(664&〜umask)的值,其中umask是文件模式创建掩码,通常默认设置为022。这就是为什么您的文件权限设置为644,因为0666&〜022 = 0644;即,rw-r--r--。

为了保持所需的权限,您必须将进程的umask设置为0000。

有关open的文档:https://man7.org/linux/man-pages/man2/open.2.html

搜索umask

如何设置umask:https://man7.org/linux/man-pages/man2/umask.2.html

或者更好的做法是在关闭后通过chmod设置文件权限。参见Andrew Henle的评论。

英文:

The file mode is set to the value of (664 & ~umask), where umask is a file mode creation mask, typically set to 022 by default. That is why your file permission is set to 644, because 0666 & ~022 = 0644; i.e., rw-r--r--.

In order to keep your desired permissions you have to set your process umask to 0000.

Docs for open: https://man7.org/linux/man-pages/man2/open.2.html

Search for umask.

How to set umask: https://man7.org/linux/man-pages/man2/umask.2.html

Or better, set file permissions by chmod after close. See comment by Andrew Henle below.

huangapple
  • 本文由 发表于 2023年5月7日 15:11:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定