Open () does not correctly set file permissions

I am creating a file using the following code:

#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> int main() { const char* filename = "./test.out"; int fd; if(-1 == (fd = open(filename, O_CREAT|O_RDWR, 0666))) { perror("Error"); errno = 0; } else puts("File opened"); if(-1 == (close(fd))) { perror("Error"); errno = 0; } else puts("File closed"); return 0; } 

I specify the mode argument as 0666 , which should provide read, write access to everyone. However ls -l shows

-rw-r--r-- 1 kmehta users 0 2012-01-29 16:29 test.out

As you can see, write permissions are granted only to the owner of the file. I do not know why everyone else did not get permission correctly. chmod a+w test.out sets permissions correctly.

Code compiled as gcc -Wall test.c

Features: gcc v 4.5.0 on Opensuse 11.3 64 bit

+9
source share
2 answers

The mode argument to open indicates the maximum permissions. The umask setting is then applied to further restrict permissions.

If you need to set permissions to 0666, you will need to use fchmod on the file descriptor after a successful open, or use umask to set the process permissions mask before opening.

+17
source

The execution of this code is:

 #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main(void) { int fd; if((fd = open("new.file",O_CREAT,S_IRWXU | S_IRWXG | S_IRWXO)) == -1) { perror("open"); return 1; } close(fd); return 0; } 

on my linux field, where umask returns 0022 , gives me a file with the following attributes:

-rwxr-xr-x 1 daniel daniel 0 Jan 29 23:46 new.file

So, as you can see, umask masks the write bits in my case. This is similar to the same on your system.

+5
source

All Articles