umask和chmod异常行为

时间:2019-10-19 12:16:07

标签: c linux system-calls

我正在尝试编写一个简单的程序,该程序使用 umask chmod 系统调用来更改文件权限,但是文件权限不会按预期的那样更改。

这是我尝试过的:

  • umask 设置为0;
  • 如果文件不存在,则使用O_CREAT标志通过 open 系统调用创建该文件,然后将特权设置为通过命令行参数传递的 mode ;
  • 如果文件已存在,请通过 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 均未能按预期设置权限。怎么了?

1 个答案:

答案 0 :(得分:1)

我创建和测试程序的文件是在Windows主机和Linux虚拟机之间的共享文件夹中创建的。我已经从Linux启动该程序,试图更改我不是所有者的文件的特权-它是Windows主机,这就是为什么它不允许我更改特权。

相关问题