umask

umask

用户权限掩码,用来设定 当前用户在创建文件或目录时的默认权限 。Linux 中,普通文件的默认最大权限是 0666(rw- rw- rw-)。即没有可执行的权限,如果非要有,就通过 chmod 来添加。而目录默认的最大权限为 0777(rwx rwx rwx),所有权限都开放。

查看当前用户权限掩码

$ umask
002

权限掩码可以这样理解:

1.  去掉 默认最大权限中与 umask 中相对应的位,就得到创建的文件或目录的默认权限。如:

普通文件默认最大权限为 0666 ,即 rw- rw- rw- ,掩码为 002,即 --- --- -w-,去掉对应位的 w,剩下的就是 rw- rw- r-- ,也就得到文件的默认权限。

2.  默认最大权限与掩码取反后相与就得到默认权限,如:0666 & (~002) = 0664

如:

$ umask
002
$ touch test
$ mkdir testdir
$ ls -l
-rw-rw-r--  1 shelmean shelmean         0 Aug  7 13:25 test
drwxrwxr-x  2 shelmean shelmean      4096 Aug  7 13:25 testdir

正如之前说 open 函数通过 O_CREAT 标志创建文件时,需要第三个参数 mode 来请求设定文件的权限,有可能设置不成功,就像当设置为 0666 时,其权限仍然为 664(默认权限),就是因为 umask 的原因。

如:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    /* 定义文件描述符并初始化为 -1 */
    int fd = -1;
    /*想要创建一个权限为 rw- rw- rw- 的文件,8进制表示为 0666*/
    if ((fd = open("test.txt",O_RDONLY | O_CREAT | O_EXCL, 0666)) == -1)
    {
        perror("open.txt open failed");
    }
    close(fd);
    return 0;
}

运行结果

$ ./a.out 
$ ls -l
-rw-rw-r-- 1 shelmean shelmean    0 Aug  7 21:01 test.txt

可以看到创建的文件权限并不是 rw- rw- rw- ,而是默认的文件权限。这是因为 umask 为 002,它会拿掉 其他(other)用户  权限,因此变成了 rw- rw- r-- 。

再如:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    /* 定义文件描述符并初始化为 -1 */
    int fd = -1;
    /*想要创建一个其他用户具有写权限的文件*/
    if ((fd = open("test.txt",O_RDONLY | O_CREAT | O_EXCL, 0446)) == -1)
    {
        perror("open.txt open failed");
    }
    close(fd);
    return 0;
}

运行结果

$ ./a.out
$ ls -l
-r--r--r-- 1 shelmean shelmean    0 Aug  7 21:07 test.txt

发现 其他(other)用户  权限被拿掉了。因为 umask 为 002 。也可以理解为 0446 & (~002) = 444 ( r-- r-- r-- )

umask的使用

       #include <sys/types.h>
       #include <sys/stat.h>

       mode_t umask(mode_t mask);

如:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    /* 定义文件描述符并初始化为 -1 */
    int fd = -1;
    umask(0);//umask 为 000
    if ((fd = open("test.txt",O_RDONLY | O_CREAT | O_EXCL, 0446)) == -1)
    {
        perror("open.txt open failed");
    }
    close(fd);
    return 0;
}

运行结果

$ ./a.out
$ ls -l
-r--r--rw- 1 shelmean shelmean    0 Aug  7 21:23 test.txt

成功创建权限为 0446 即 r-- r-- rw- 的普通文件。

原文地址:https://www.cnblogs.com/shelmean/p/9436425.html