open()函数未正确设置文件权限

9

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

#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 on Opensuse 11.3 64 bit


你尝试过使用常量标志吗?例如S_IRUSR,S_IRGRP等。 - Sergey Kalinichenko
@dasblinkenlight 使用常量并没有帮助。这是一个umask问题,现在使用文件打开后的fchmod,如答案所示。 - Korizon
2个回答

19

open函数的mode参数指定了文件的最大权限。然后使用umask设置来进一步限制权限。

如果您需要将权限明确设置为0666,则需要在打开成功后使用fchmod函数对文件句柄进行操作或使用umask 在打开之前设置进程的权限掩码。


2
两年后,我在做计算机科学作业时偶然发现了这个答案。我不知道我需要使用fchmod来显式地将权限设置为0666 - yiwei

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

在我的Linux系统中,umask返回0022,创建的文件具有以下属性:-rwxr-xr-x 1 daniel daniel 0 Jan 29 23:46 new.file。因此,可以看到,在我的情况下,umask掩盖了写入位。看起来在你的系统上也是一样的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接