open() not setting file permissions correctly

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

If you need to make the permissions be 0666 specifically you will need to use fchmod on the file handle after the open succeeds or use umask to set the process’ permissions mask before the open.


Executing this code :

#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 box, 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, the umask masks out the write bits in my case. It looks like it's the same on your system, too.

Tags:

C

Posix