曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 5896|回复: 0
打印 上一主题 下一主题

[文件I/O] umask() -- 修改系统 umask 值

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2010-5-30 14:17:43 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
原型
#include <sys/types.h>
#include <sys/stat.h>
mode_t umask(mode_t mask);


说明
在创建文件时,系统需要给该文件一个默认的权限,根据系统的安全性,用户可以自己设置当前系统,创建一个普通文件时的默认权限是 0666-umask,如果创建一个目录,默认权限为 0777-umask。比如在shell 下输入命令:
 umask
0022
现在创建一个文件并查看其权限:
touch c.txt
ll c.txt
-rw-r--r-- 1 groad users 0 05-30 12:39 c.txt
由上可见,新创建文件权限是由 0666 和 022 相异或所得。
目录也是如此:
mkdir
drwxr-xr-x 2 groad users  4096 05-30 12:42 temp_dir
如果修改当前的屏蔽码,再创建文件,那么:
umask 0000

ll d.txt
-rw-rw-rw- 1 groad users 0 05-30 12:43 d.txt

在 Linux 下,设置创建文件掩码函数为 umask()。

示例程序
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char **argv)
{
    if (creat ("test01", S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) < 0) {
        perror ("creat");
        exit (EXIT_FAILURE);
    }

    umask (0);
    if (creat ("test02", S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) < 0) {
        perror ("creat");
        exit (EXIT_FAILURE);
    }

    umask (S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
    if (creat ("test03", S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) < 0) {
        perror ("creat");
        exit (EXIT_FAILURE);
    }

    return (0);
}
运行与输出
> ll test01
-rw-r--r-- 1 groad users 0 05-30 14:14 test01
> ll test02
-rw-rw-rw- 1 groad users 0 05-30 14:14 test02
> ll test03
-rw------- 1 groad users 0 05-30 14:14 test03
创建 test01 文件按照系统默认的屏蔽码。
创建 test02 文件时将屏蔽码设置为0,即完全不对新创文件做任何的屏蔽。
创建 test03 文件时屏蔽码已经设置组读写、其他读写4个权限位。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-4 16:31 , Processed in 0.097140 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表