英文:
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<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?
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论