Rohit Upadhyay
Rohit Upadhyay

Reputation: 129

What is the default access mode of files created with open() function in C?

I wrote the following C code to open a non-existent file.

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

int main(){
    int fd = open("test.c",O_WRONLY | O_CREAT);
    printf("%d\n",fd);
    close(fd);
}

Although the umask is set to 0002 when I run the ls -l command, I get the following output for the file I created.

-r--rws--T 1 urohit011 urohit011     0 Feb 14 22:35 test.c

The access mode changes when I run the code with a new file name. I have two questions here.

Upvotes: 0

Views: 2670

Answers (2)

Luis Colorado
Luis Colorado

Reputation: 12708

The access mode on a file created must be specified on the open(2) call as the third parameter to it. Because of the way C does things, that third parameter (allowed depending on flags used in the second parameter) makes the open(2) call variadic, and the compiler doesn't check if you have provided the right number of parameters.

Due to this, if you don't pass a third parameter, it will not be pushed onto the stack by the calling code, but the function will use whatever is there in the position for the third parameter. You got a Undefined Behaviour issue, with the best result being getting a new file with the wrong access mode. You can get a crash if the open(2) routine modifies the third parameter.

The access mode you provide will be finally modified by the umask bits to get the final mode of the created file.

Upvotes: 0

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136505

The mode / permission bits are specified by the third argument of open call. You do not provide that argument and that is a silent programming error when O_CREAT is used:

This argument (mode) must be supplied when O_CREAT or O_TMPFILE is specified in flags; if neither O_CREAT nor O_TMPFILE is specified, then mode is ignored.


Shouldn't the default access mode of that file be 664 since the umask is 0002

Default mode must be explicitly provided:

open("test.c",O_WRONLY | O_CREAT, 0666)
                                   ^^

Why the access mode changes when the code is run with a new file name ?

open is a variadic function that accepts 2 or more arguments:

int open(const char* file, int flag, ...);

Hence, the third argument of the function gets initialized with an indeterminate value if no value is provided. There is no compiler error if only 2 arguments are provided. On the other hand, it is not an error to always provide the third argument to open call.

Upvotes: 5

Related Questions