2012-01-29 154 views
7

我创建使用下面的代码文件:的open()未设置文件权限正确

#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; 
} 

我指定的mode参数作为0666,应授予读取,写入访问给大家。然而,ls -l显示

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

正如你所看到的,写权限仅仅授予文件的所有者。我不知道为什么其他人没有正确授予权限。 chmod a+w test.out虽然正确设置权限。

代码编译为gcc -Wall test.c

规格:GCC v 4.5.0在openSUSE 11.3 64个

+3

检查umask。检查umask。 – wildplasser 2012-01-29 22:40:07

+0

你是否尝试使用常量来表示标志,例如S_IRUSR,S_IRGRP等? – dasblinkenlight 2012-01-29 22:41:39

+0

@dasblinkenlight使用常量没有帮助。这是一个umask问题,现在打开文件后使用fchmod,如答案 – jitihsk 2012-01-29 22:59:18

回答

15

mode参数open指定最大允许权限。然后应用umask设置来进一步限制权限。

如果您需要将权限设置为0666,则在打开成功后,您需要在文件句柄上使用fchmod

+2

+1所示。两年后,我在做CS作业时偶然发现了这个问题。我不知道我必须'fchmod'才能将权限明确设置为'0666' – yiwei 2014-10-21 01:00:55

3

执行此代码:

#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; 
} 

在我的Linux机器,其中umask回报0022,使我具有以下属性的文件:

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

所以,你可以看到,在我的情况下,umask掩盖了写入位。它看起来在你的系统上也是一样的。