Issue
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?
Solution
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.
Answered By - Andrey Ivanov Answer Checked By - Willingham (WPSolving Volunteer)