赞
踩
- #include<sys/stat.h>
- mode_t umask(mode_t cmask);
umask函数为进程设置文件模式创建屏蔽字,并返回改动之前的值。
这个函数的功能比较奇葩,他实际上是规定了创建文件时哪些功能是不能用的,即便你创建时赋予了这个功能,他也将其无视。具体来说,如果umask中设置了“用户读”,则你创建的任何文件必然没有“用户读”权限,哪怕你在open或creat的时候明文表示你需要“用户读”权限。
举例如下:
- #include <stdio.h>
- #include <stdlib.h>
- #include <memory.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <fcntl.h>
-
- void err_sys(char *);
- void err_sys(char *err_txt)
- {
- printf("%s\n",err_txt);
- exit(1);
- }
-
- int main(int argc, char* argv[])
- {
- //4.9 umask 文件模式创建屏蔽字
- printf("old umask = %d\n", umask(0));
- if(creat("jxl.txt", S_IRUSR) < 0)
- err_sys("creat error for jxl.txt");
-
- umask(S_IRUSR);
- if(creat("hy.txt", S_IRUSR) < 0)
- err_sys("creat error for hy.txt");
-
- exit (0);
- }

创建hy.txt前将umask的“用户读”置位,实际上代表屏蔽“用户读”权限,然后再以“用户读”的方式创建文件
执行结果如下:
程序打印出了系统默认的umask值,为2,代表系统默认不开放“其他写”权限。
jxl.txt的权限没有被限制,所以最终其按照我们的设定获得了“用户读”权限
hy.txt由于屏蔽了“用户写”,但是又按照“用户写”来创建文件,最终导致其没有获得任何权限。
注意:
更改进程的文件模式创建屏蔽字,并不影响其父进程的文件模式创建屏蔽字。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。