umask 函数

现在我们已经描述了文件相关联的九个权限位,我们可以描述每个进程的文件模式创建的屏蔽字(mask)。
umask函数为进程设置 文件模式创建屏蔽字(file mode creation mask)平且返回上次的值。(这个函数时一些不返回错误中的一个).

#include <sys/stat.h>

mode_t umask(mode_t cmask);
 returns:previous file mode creation mask
参数cmask别格式成按位或上图4.6中的任意常量:S_IRUSR,S_IWUSR, 等等。

无论何时进程创建一个文件或是一个新目录the file mode creation mask被使用。(回顾我们在3.3节和3.4节对open和creat函数的描述。它们都接受Mode参数来指定新文件的访问权限位。)我们在4.20节描述如何创建一个新的目录。在文件模式创建屏蔽字为1的位,则文件mode为0。

例如:

在图4.9的程序创建两个文件,一个umask字为0,另一个禁止了所有组合另外的权限位。

如果你运行这个程序,我们将看到如何设置权限位。
 
 $ umask                    first print the current file mode creation mask
       002
       $ ./a.out
       $ ls -l foo bar
       -rw------- 1 sar            0 Dec 7 21:20 bar
       -rw-rw-rw- 1 sar            0 Dec 7 21:20 foo
       $ umask                    see if the file mode creation mask changed
       002

Figure 4.9. Example of umask function

#include "apue.h"
#include <fcntl.h>

#define RWRWRW (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)

int
main(void)
{
    umask(0);
    if (creat("foo", RWRWRW) < 0)
        err_sys("creat error for foo");
    umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
    if (creat("bar", RWRWRW) < 0)
        err_sys("creat error for bar");
    exit(0);
}

大部分unix系统绝不处理umask值。通常在登录时的shell的start-up 文件设置一次,并绝不改变。
然而,当写程序创建新文件的时候,如果我们想保证指定的存取权限位被有效。当程序运行时我们必须改变umask值,例如,如果你想确保任何人都能读文件,我们将设置umask为0。另外,当我们的进程运行时可能导致权限位被置0而影响到umask值。

在前面的例子中,在我们运行程序前后,我们使用shell的umask命令打印文件模式创建屏蔽字。这告诉我们改变进程的文件模式创建屏蔽字并不能影响他父亲的umask(通常是shell).所有的shell都有内置的umask命令可以设置或打印当前的file mode creation mask.

用户可以设置umask值以控制创建文件的默认权限。这个值用八进制表达,一个位代表一个权的屏蔽,如图4.10。权限可以拒绝设置相应的位。普通的Umask值是002允许别人写你的文件,022代表组成员和别人可以写你的文件,027代表组成员可以写你的文件并且别人可以读写并执行你的文件。

Figure 4.10. The umask file access permission bits Mask bit
 Meaning
 
0400 user-read
 
0200 user-write
 
0100 user-execute
 
0040 group-read
 
0020 group-write
 
0010 group-execute
 
0004 other-read
 
0002 other-write
 
0001 other-execute
 
The Single UNIX Specification requires that the shell support a symbolic form of the umask command. Unlike the octal format, the symbolic format specifies which permissions are to be allowed (i.e., clear in the file creation mask) instead of which ones are to be denied (i.e., set in the file creation mask). Compare both forms of the command, shown below.

       $ umask                        first print the current file mode creation mask
       002
       $ umask -S                     print the symbolic form
       u=rwx,g=rwx,o=rx
       $ umask 027                    change the file mode creation mask
       $ umask -S                     print the symbolic form
       u=rwx,g=rx,o=


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值