函数umask为进程设置权限掩码。并且返回之前的掩码值。它是为数不多的没有出错返回的函数。函数原型和依赖的头文件如下所示:
函数的参数就是文件权限。mask参数的值是有S_IRUSR等9个常量按位与来决定的。当某一个常量出现在参数mask中,那么之后创建文件或目录的时候,就会失去相应的权限。
注意:在某一个进程中更改了umask,这并不影响其父进程的umask值(父进程通常是shell)。下面这个例子很好的体现了这一点。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int fd = open("a",O_RDWR | O_APPEND | O_CREAT,0664);
if (-1 == fd)
{
perror("open file");
exit(1);
}
umask(0222); //更改权限掩码,屏蔽写权限
close(fd);
fd = open("b",O_RDWR | O_APPEND | O_CREAT,0664);
if (-1 == fd)
{
perror("open file");
exit(1);
}
close(fd);
return 0;
}
运行结果:在执行之前是0002,执行了上述代码以后,仍旧是0002。但是在进程执行的时候,创建的文件权限确实被进程中设置的权限掩码限制了。