我正在使用以下代码在 C 中创建一个文件:
int outfd = open(arg,O_CREAT|O_TRUNC|O_WRONLY, f_per);
f_per
是文件权限编号。
将 f_per
设置为 0644
,执行代码并执行 ls -l 给我设置为 -rw-r-- 的(输出)文件权限r--
这是预期的。但是,将内容设置为 0777 会授予 -rwxrwxr-x
而不是 -rwxrwxrwx
的权限。知道为什么会这样吗?
最佳答案
根据 POSIX page for the open
call ,在 O_CREAT
下:
... the access permission bits of the file mode shall be set to the value of the argument following the oflag argument taken as type
mode_t
modified as follows: a bitwise AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask.
模式创建掩码(或 umask)可以被认为是一个减法掩码。例如,如果您在文件模式创建掩码为 --------w-/0002
时尝试创建具有权限 rwxrwxrwx/0777
的文件,则您实际上最终会是:
rwxrwxrwx
& rwxrwxr-x (complement of -------w-)
=========
rwxrwxr-x
这似乎是您遇到的情况。
如果你想实际创建一个特定权限的文件,你可以通过将它设置为零(然后恢复它)来暂时禁用 umask,就像:
mode_t oldmask = umask(0); // needs sys/stat.h
int outfd = open(arg, O_CREAT|O_TRUNC|O_WRONLY, 0777);
umask(oldmask);
关于c - C中的文件创建权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28234136/