open() not setting file permissions correctly

http://stackoverflow.com/questions/9057419/open-not-setting-file-permissions-correctly


I create a file using the code below:

#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 grant read,write access to everyone. However, an ls -l shows

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

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

Code compiled as gcc -Wall test.c

Specs: gcc v 4.5.0 on Opensuse 11.3 64 bit

share | improve this question
 
3 
check umask. check umask. –  wildplasser Jan 29 '12 at 22:40
 
Did you try using constants for flags, e.g. S_IRUSR, S_IRGRP, etc.? –  dasblinkenlight Jan 29 '12 at 22:41
 
@dasblinkenlight Using constants didnt help. It was a umask issue, using fchmod after file open now as shown in the answer –  KVM Jan 29 '12 at 22:59

2 Answers

up vote 6 down vote accepted

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.

share | improve this answer
  

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.

share | improve this answer
  

Your Answer















 

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值