【问题标题】:umask and chmod unexpected behaviourumask 和 chmod 意外行为
【发布时间】:2019-10-19 12:16:07
【问题描述】:

我正在尝试编写使用 umaskchmod 系统调用更改文件权限的简单程序,但文件权限没有按预期更改。

这是我尝试过的:

  • 设置umask为0;
  • 如果文件不存在,则由 open 系统调用使用 O_CREAT 标志创建,然后将权限设置为通过命令行参数传递的 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

umaskchmod 都未能按预期设置权限。怎么了?

【问题讨论】:

  • 我没有立即发现任何问题,我在我的机器(MacOS、clang)上尝试了您的代码,它运行良好。所以我不知道为什么它不适合你。
  • 看起来您正在以 root 身份运行该程序。我不希望这会产生任何影响,但是如果以普通用户身份运行,您会得到相同的行为吗?
  • 对于故障排除,考虑在 strace (strace ./a.out ...) 下运行代码。这将为您提供每个系统调用的输入和结果。
  • @SteveSummit 我已经意识到问题所在:因为我在虚拟机上使用 Linux,所以我在 Windows 主机的共享文件夹中创建了文件。因此,我实际上不是该文件的所有者,并且主机不允许我更改虚拟 Linux 机器的权限。

标签: c linux system-calls


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 2011-01-28
    • 2021-09-14
    • 2017-03-27
    相关资源
    最近更新 更多