说明:只供学习交流,转载请注明出处
umask用于影响新建立文件的默认权限。当新建立一个文件或目录时,系统会根据umask的值来“剥夺”文件或目录的相应权限。例如,如果umask的值是022的话,表示新创建的文件的权限是666-022=644(出于安全考虑,新创建的文件没有执行权限。因此,权限是(666-022),而不是(777-022)),即“rw-r--r--”的形式)对目录而言是(777-022),即“rwxr-xr-x”的形式。
Linux系统同样提供了umask函数用于在程序中修改umask的值,以确定程序创建的文件的权限。函数具体信息见下表:
umask函数
头文件 |
<sys/types.h> <sys/stat.h> | ||
函数形式 |
mode_t umask(mode_t mask); | ||
返回值 |
成功 |
失败 |
是否设置errno |
修改前的umask |
系统调用总是成功 |
无相关信息 |
说明:umask函数用于修改进程的文件创建权限,umask往往与open、mkdir函数或其他的系统调用搭配使用,用于创建新的文件时获得不同的权限。默认情况下,进程的umask值为S_IWGRP|S_IWOTH(也就是八进制的022)。
错误信息:
该系统调用总是执行成功,因此没有错误信息。
实例:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void)
{
int fd1;
int fd2;
//创建名为test的文件,权限为777,即所有用户都拥有读写和执行权限
fd1 = open("test", O_CREAT | O_RDWR, 0777);
if ( fd1 < 0 )
{
perror("Cannot create the test file");
return (1);
}
close(fd1);
struct stat file_stat;
//调用stat函数获得test文件的权限
if (stat("test", &file_stat) == -1)
{
perror("Cannot get the information of the file!\n");
return (1);
}
//输出权限
printf("Permission is : %o\n", file_stat.st_mode & 0x1ff);
//调用umask函数修改进程创建文件的umask的值
//除了使用下面的形式,还可以使用umask(077)这样的形式
umask(S_IWGRP | S_IRGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH);
//创建名为test1的文件,权限为777
fd2 = open("test1", O_CREAT | O_RDWR, 0777);
if ( fd2 < 0 )
{
perror("Cannot create the test file");
return (1);
}
close(fd2);
//调用stat函数获得test1的权限
if ( stat("test1", &file_stat) == -1 )
{
perror("Cannot get the information of the file!\n");
return (1);
}
//输出修改umask后的test1的权限值
printf("After Modify umask value, Premission is : %o\n", file_stat.st_mode & 0x1ff);
return (1);
}
运行结果:
[root@localhost test]# ./umask
Permission is : 755
After Modify umask value, Premission is : 700
[root@localhost test]# ll
total 96
-r--r--r-x 1 root root 7778 Apr 30 01:43 chdir
-rw-rw-rw- 1 root root 1398 Apr 30 01:43 chdir.cpp
-rwxr-xr-x 1 root root 5046 May 1 01:03 chmod
-rw-rw-rw- 1 root root 476 May 1 01:03 chmod.c
-rwxr-xr-x 1 root root 5062 May 1 01:43 chown
-rw-rw-rw- 1 root root 393 May 1 01:43 chown.c
-r--r--r-x 1 root root 7102 Apr 29 23:33 getcwd
-rw-rw-rw- 1 root root 560 Apr 29 23:33 getcwd.cpp
-rw-r--r-- 1 root root 0 May 2 22:03 hello
-rwxr-xr-x 1 root root 6145 Apr 30 18:20 mkdir
-rwxr--r-- 1 root root 337 Apr 30 18:20 mkdir.cpp
-rwxr-xr-x 1 root root 7440 Apr 30 01:23 pathconf
-rw-rw-rw- 1 root root 966 Apr 30 01:24 pathconf.cpp
-rwxr-xr-x 1 root root 5860 Apr 30 23:33 stat
-rwxr--r-- 1 root root 1778 Apr 30 23:33 stat.c
-rwxr-xr-x 1 root root 0 May 2 22:02 test
-rwx------ 1 root root 0 May 2 22:02 test1
-rwxr-xr-x 1 root root 5690 May 2 22:02 umask
-rw-rw-rw- 1 root root 1515 May 2 22:02 umask.c