1

我正在使用open系统调用创建一个具有完全权限(777)的文件,但是当我这样做时,ls -l我只能看到权限为(755)。你能告诉为什么文件权限不是777吗?

代码

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int main()
{
        int fd;

        /* Creates a file with full permission*/
        fd = open("test", O_CREAT | O_RDWR | O_APPEND, 0777);

        if (fd = -1)
        {
                return -1;
        }

        close(fd);
}

输出

     $ ls -l
    -rwxr-xr-x 1 ubuntu ubuntu    0 2012-09-19 11:55 test
4

3 回答 3

7

There's a value maintained by the system called the umask; it is a property of the process, just like the PID (process ID) or EUID (effective user ID) is. It will be set to 022 (octal), which indicates that the system should remove the group and other write permission from files that are created.

You can call umask(0); before using open() so that the mode you specify in open() won't be altered. You should certainly do this to demonstrate that umask is the issue. However, it is generally best to let the user's choice of umask prevail — I for one get very stroppy if a program doesn't obey my umask setting; it tends not to be used again after I spot and verify the problem.

The shell also has a (built-in) command umask which you can use. The 022 value is a sensible default; most of the time, you do not want just anybody writing to your files.

于 2012-09-19T06:31:57.233 回答
3

The permissions of a created file are restricted by the process's current umask -- your current umask is 022, so group and world write are always disabled by default. (Which is a good thing, in most cases.) If you really want a group- and world-writable file, you will need to temporarily set umask(0) while creating this file (make sure to save the old value returned by the system call, and set it back afterwards!), or "manually" set the file's permissions using chmod().

于 2012-09-19T06:31:58.550 回答
0

umask将返回掩码的原始值,因此要暂时重置它,您只需要做

#include <sys/types.h>
#include <sys/stat.h>

mode_t old_mask = umask(0);
...
umask(old_mask);

fchmod 尽管在打开文件后使用可能更可取- 这将避免更改进程全局状态的问题:

fd = open("test", O_CREAT | O_RDWR | O_APPEND, 0777);
if (fd < 0) { ... }
int rv = fchmod(fd, 0777);
if (rv < 0) { /* fchmod errored */ }
于 2019-08-08T12:31:22.603 回答