umask Function

来源:互联网 发布:御膳房算法平台 编辑:程序博客网 时间:2024/06/07 06:42

umask - set file mode creation mask(文件模式创建掩码)
系统调用umask给进程设置file mode creation mask并且返回之前的值(这是少数不返回错误值的函数之一)
Linux man手册中umask原型如下:

#include <sys/types.h>#include <sys/stat.h>mode_t umask(mode_t mask);//Returns: previous file mode creation mask

umask的参数mask是9个访问权限常量(S_IRUSR,S_IWUSR…)中部分常量位与(bitwise OR)形成的.只要进程创建了新文件或者新目录,file mode creation mask就会被用上。在掩码中任何被打开的bit相应地在file‘smode中就会被关闭。

Example

创建两个文件,一个umask参数为0,一个umask参数关闭了所有组(group)和other的访问权限。

#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdio.h>#include <string.h>#include <errno.h>#include <stdlib.h>#define RWRWRW (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)int main(){    umask(0);    if(open("rwall", O_CREAT, RWRWRW) < 0) //enable read and write for all users    {        fprintf(stderr, "rwrwrw open error: %s!\n", strerror(errno));  //open error        exit(-1);    }    umask(S_IRGRP|S_IWGRP); //disable group for read and write    if(open("nogrp", O_CREAT, RWRWRW) < 0)    {        fprintf(stderr, "nogrp open error: %s!\n", strerror(errno));   //open error        exit(-1);    }    return 0;}

运行好后,调用ls -l查看文件权限
结果

-rw-rw-rw- 1 rwall-rw----rw- 1 nogrp

大部分Unix系统的用户从来不处理他们umask的值。纵使在登陆的时候,通过shell的start-upfile设置一次,之后就不再改变。无论如何,在我们创建新文件需要确定特定权限位(permission bit)被使能,我们必须在进程运行时修改umask的值。例如,我们想确保任何人可以读取文件,我们需要设置umask为0.

进程中改变了mask并不会影响进程父亲(一般是shell)的mask。所有的shell都有umask command可以查看或者设置file mode creation mask

通过设置相应位来disable相应权限,如下表(8进制格式)。
figure 4.10
一些常用的umask值是002—防止other write你的文件(shell输入umask默认为该值);022—防止group成员或者other用户来write你的文件;027—防止组成员写你的文件,防止other用户write、read、execute你的文件。

shell支持umask command的符号形式。与八进制形式不同,符号形式指定了允许的权限(clear bits in the file mode creation mask)而不是拒绝的权限。

比较两者形式:

$umask002$umask -Su=rwx,g=rwx,o=rx$umask 027$umask -Su=rwx,g=rx,o=
0 0