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

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

[cpp] view plain copy
  1. #include<sys/stat.h>  
  2. int chmod(const char* pathname, mode_t mode); //通过文件名对指定的文件进行操作  
  3. int fchmod(int filedes, mode_t mode); //通过文件描述符对以打开的文件进行操作  
  4. //如果成功返回0,失败返回-1.  
为了改变现有文件的权限位,进程的有效用户ID必须等于文件的所有者ID,或者进程具有超级用户权限。

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

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

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

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


实践:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <sys/stat.h>  
  3.   
  4. int main(void){  
  5.         if(chmod("a",S_IRWXU | S_IRWXO | S_ISUID | S_ISVTX)<0){  
  6.                 perror("chmod");  
  7.                 return -1;  
  8.         }  
  9.         return 0;  
  10. }  

运行结果:

[email protected]:~/apue$ ll a
-rw-rw-r-- 1 yan yan 0 Jun 12 13:53 a
[email protected]:~/apue$ ./a.out
[email protected]:~/apue$ ll a
-rws---rwt 1 yan yan 0 Jun 12 13:53 a*


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

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <sys/stat.h>  
  3.   
  4. int main(void){  
  5.         struct stat statbuf;  
  6.   
  7.         if(stat("a", &statbuf) < 0){  
  8.                 perror("stat");  
  9.                 return -1;  
  10.         }  
  11.   
  12.         if(chmod("a",(statbuf.st_mode & ~S_IRUSR)|S_IWGRP)<0){ //去除文件a的用户读,增加组写  
  13.                 perror("chmod");  
  14.                 return -1;  
  15.         }  
  16.         return 0;  
  17. }  
运行结果:

[email protected]:~/apue$ ll a
-rws---rwt 1 yan yan 0 Jun 12 13:53 a*
[email protected]:~/apue$ ./a.out
[email protected]:~/apue$ ll a
--ws-w-rwt 1 yan yan 0 Jun 12 13:53 a*