简体   繁体   English

如何在 Posix 上使用 C 创建具有正确权限的目录

[英]How to create directory with right permissions using C on Posix

I am trying to write a simple C program that creates directories (a mkdir clone.).我正在尝试编写一个简单的 C 程序来创建目录(一个 mkdir 克隆。)。 This is what I have so far:这是我到目前为止所拥有的:

#include <stdlib.h>
#include <sys/stat.h> // mkdir
#include <stdio.h> // perror

mode_t getumask()
{
    mode_t mask = umask(0);
    umask (mask);
    return mask;
}

int main(int argc, const char *argv[])
{
    mode_t mask = getumask();
    printf("%i",mask);

    if (mkdir("trial",mask) == -1) {
        perror(argv[0]);
        exit(EXIT_FAILURE);
    }
    return 0;
}

This code creates directory with d--------- but I want it to create it with drwxr-xr-x like mkdir do?此代码使用d---------创建目录,但我希望它像 mkdir 一样使用drwxr-xr-x创建它? What am I doing wrong here?我在这里做错了什么?

You seem to be misunderstanding what umask is used for. 你似乎误解了umask的用途。 It sets/retrieves the process's file mode creation mask, which in turn is used to turn off bits in the file mode you specify in calls like mkdir , like this (pseduo-code): 它设置/检索进程的文件模式创建掩码,该掩码又用于关闭您在mkdir等调用中指定的文件模式中的位,如下所示(pseduo-code):

real_mode = requested_mode & ~umask

So in your code, since you pass in the value of the umask itself, you end up specifying permissions as zero, which is exactly what you see. 因此,在您的代码中,由于您传入了umask本身的值,因此最终将权限指定为零,这正是您所看到的。

Instead, you should specify the permissions you want in the call to mkdir , like this: 相反,您应该在调用mkdir指定所需的权限,如下所示:

mkdir("trial", 0755)

Disclaimer : I extracted this answer from the OPs question.免责声明:我从 OP 问题中提取了这个答案。 Answers should not be contained in the question itself .答案不应包含在问题本身中。


Answer provided by yasar : yasar提供的答案:

This is the working solution for me:这是我的工作解决方案:

int main(int argc, const char *argv[])
{
    if (mkdir("trial",0777) == -1) {
        perror(argv[0]);
        exit(EXIT_FAILURE);
    }
    return 0;
}

Setting right permissions according to umask is automatically handled.根据 umask 设置正确的权限是自动处理的。 So I only needed to call mkdir with full permissions, and that gets chopped according to current umask.所以我只需要以完全权限调用 mkdir,然后根据当前的 umask 进行切割。

As Eric says, umask is the complement of the actual permission mode you get. 正如Eric所说,umask是您获得的实际权限模式的补充。 So instead of passing mask itself to mkdir() , you should pass 0777-mask to mkdir() . 因此,不应将掩码本身传递给mkdir() ,而应将0777-mask传递给mkdir()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM