我正在尝试编写一个简单的程序,该程序使用 umask 和 chmod 系统调用来更改文件权限,但是文件权限不会按预期的那样更改。
这是我尝试过的:
#define _XOPEN_SOURCE 700
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define check_error(expr, userMsg) \
do { \
if (!(expr)) { \
perror(userMsg); \
exit(EXIT_FAILURE); \
} \
} while(0)
int main(int argc, char** argv)
{
check_error(3 == argc, "use: ./umask path mode");
mode_t oldUmask = umask(0);
long mode = strtol(argv[2], NULL, 8);
int fd = open(argv[1], O_WRONLY|O_CREAT|O_EXCL, mode);
if (-1 == fd) {
if (EEXIST == errno) {
printf("[file already exists]\n");
check_error(-1 != chmod(argv[1], mode), "chmod failed");
} else {
perror("open failed");
exit(EXIT_FAILURE);
}
} else {
close(fd);
}
umask(oldUmask);
exit(EXIT_SUCCESS);
}
编译后我尝试过:
./umask 1.txt 0744
期望的特权为-rwxr--r--,但在
之后ls -l
我得到:
-rwxrwxrwx 1 root root 0 окт 19 14:06 1.txt
再次,
./umask 1.txt 0744
这一次我希望 chmod 会在内部更改现有文件的特权,但是在列出之后,我会得到相同的结果:
[file already exists]
-rwxrwxrwx 1 root root 0 окт 19 14:06 1.txt
umask 和 chmod 均未能按预期设置权限。怎么了?
答案 0 :(得分:1)
我创建和测试程序的文件是在Windows主机和Linux虚拟机之间的共享文件夹中创建的。我已经从Linux启动该程序,试图更改我不是所有者的文件的特权-它是Windows主机,这就是为什么它不允许我更改特权。