第三章_文件与目录 : 函数Umask

函数Umask

#include <sys/types.h>
#include <sys/stat.h>
mode_t umask(mode_t cmask)

mode_t umask(mode_t mask);//函数原型
该函数为进程设置文件模式屏蔽字,并返回以前的值。 即在创建新文件或目录时屏蔽掉你希望新文件或新目录不应有的访问权。比如说你不希望新创建的文件或目录拥有可执行的权限,那么只需将它的可执行权限作为该函数的参数,利用该函数将其屏蔽掉。
使用如下选项分别表示文件的9种访问权限。
在这里插入图片描述
我们可以是使用此函数来设置允许 当前进程 创建的文件或目录的最大可操作权限。
比如说,当我们在一个源程序的开始加上 umask(0) 这样一句代码。那么,在这个程序里后边所有创建的文件和目录的最大权限就被限制了。只是这里的限制相当于没有限制,因为这里的0就代表的其实就是000 000 000 ,即所有的权限都没有。也就是并没有屏蔽任何权限。那么,创建文件和目录的 最大权 限依然是0777(user、group、other都拥有读、写和可执行的权利)。

转:https://blog.csdn.net/guaiguaihenguai/article/details/79934142

测试程序

#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;
}

在这里插入图片描述

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>


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


int main(void)
{
    umask(0);
    if(creat("hello", RWRWRW) < 0)
    {
        printf("creat error for hello\n");
        exit(1);
    }
    umask(S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
    if(creat("world", RWRWRW) < 0)
    {
        printf("creat error for world");
        exit(1);
    }
    exit(0);
} 

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值