现在的位置: 首页 > 综合 > 正文

《UNIX环境高级编程》笔记–chmod函数和fchmod函数

2013年04月25日 ⁄ 综合 ⁄ 共 1025字 ⁄ 字号 评论关闭

这2个函数都是用来改变现有文件的访问权限的。函数的定义如下:

#include<sys/stat.h>
int chmod(const char* pathname, mode_t mode); //通过文件名对指定的文件进行操作
int fchmod(int filedes, mode_t mode); //通过文件描述符对以打开的文件进行操作
//如果成功返回0,失败返回-1.

为了改变现有文件的权限位,进程的有效用户ID必须等于文件的所有者ID,或者进程具有超级用户权限。

参数mode是由下图中所示常量的按位或运算构成的。

上图中,有9个是文件访问权限,另外加了6项,他们是设置用户ID和设置组ID(S_ISUID和S_ISGID),粘住位(S_ISVTX),

三个组合常量(S_IRWXU,S_IRWXG,S_IRWXO)。

实践:

#include <stdio.h>
#include <sys/stat.h>

int main(void){
        if(chmod("a",S_IRWXU | S_IRWXO | S_ISUID | S_ISVTX)<0){
                perror("chmod");
                return -1;
        }
        return 0;
}

运行结果:

yan@yan-vm:~/apue$ ll a
-rw-rw-r-- 1 yan yan 0 Jun 12 13:53 a
yan@yan-vm:~/apue$ ./a.out
yan@yan-vm:~/apue$ ll a
-rws---rwt 1 yan yan 0 Jun 12 13:53 a*

如果要在原来的文件属性上加或者减属性可以先使用stat函数获取文件的mode_t,然后再进行与和或操作:

#include <stdio.h>
#include <sys/stat.h>

int main(void){
        struct stat statbuf;

        if(stat("a", &statbuf) < 0){
                perror("stat");
                return -1;
        }

        if(chmod("a",(statbuf.st_mode & ~S_IRUSR)|S_IWGRP)<0){ //去除文件a的用户读,增加组写
                perror("chmod");
                return -1;
        }
        return 0;
}

运行结果:

yan@yan-vm:~/apue$ ll a
-rws---rwt 1 yan yan 0 Jun 12 13:53 a*
yan@yan-vm:~/apue$ ./a.out
yan@yan-vm:~/apue$ ll a
--ws-w-rwt 1 yan yan 0 Jun 12 13:53 a*

抱歉!评论已关闭.