open()没有正确设置文件权限

jit*_*hsk 9 c posix

我使用以下代码创建一个文件:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我将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

规格:在Opensuse 11.3 64位上的gcc v 4.5.0

Zan*_*ynx 18

mode用于open指定允许的最大权限的参数.umask然后应用该设置以进一步限制权限.

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

  • +1两年后,我在做家庭作业时偶然发现了这个答案.我不知道为了将权限显式设置为"0666",我必须使用`fchmod` (2认同)

Dan*_*zar 5

执行此代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

在我的Linux机器上,umask返回0022,给我一个具有以下属性的文件:

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

所以,正如你所看到的,umask掩盖了我的写位.它看起来在你的系统上也是一样的.