unix环境高级编程-4.7-access函数

来源:互联网 发布:东北副食店淘宝 编辑:程序博客网 时间:2024/05/17 01:47

http://blog.csdn.net/wallwind/article/details/6889888

如前所述,当用open函数打开一个文件的时候,内核以进程的有效用户ID和有效组ID,为基础执行期访问权限测试。有时候,进程也希望按期实际用户ID,和实际组ID,来测试访问能力。

access函数是按照实际用户ID和实际组ID,进行访问权限测试的。

 

[cpp] view plaincopy
  1. #include<unistd.h>  
  2.   
  3. int access (const char*pathname,int mode);  

 

返回值:成功返回0,出错返回-1

查看GNU C函数手册

int access (const char *filename, int how) [Function]
The access function checks to see whether the file named by filename can beaccessed
in the way specified by the how argument. The how argument either can be the
bitwise OR of the flags R_OK, W_OK, X_OK, or the existence test F_OK.
This function uses the real user and group IDs of the calling process, ratherthan the
effective IDs, to check for access permission. As a result, if you use thefunction from
a setuid or setgid program (see Section 29.4 [How an Application Can Change
Persona], page 716), it gives information relative to the user who actually ranthe
program.
The return value is 0 if the access is permitted, and -1 otherwise. (In otherwords,
treated as a predicate function, access returns true if the requested access isdenied.)
In addition to the usual file name errors (see Section 11.2.3 [File NameErrors],
page 224), the following errno error conditions are defined for this function:
EACCES The access specified by how is denied.
ENOENT The file doesn’t exist.
EROFS Write permission was requested for a file on a read-only file system.
These macros are defined in the header file ‘unistd.h’ for use as the howargument to
the access function. The values are integer constants.

可知,该函数使用的是实际用户ID,和组ID,去调用进程。而不是有效ID,,去检查他的访问权限。

其中mode 是表所列常量的按位或

          

Access函数的mode常量

  

mode

  

说明

  

R_OK

 

W_OK

 

X_OK

 

F_OK

  

测试读权限

 

测试写权限

 

测试执行权限

 

测试文件是否存在

 

实例

[cpp] view plaincopy
  1. #include"apue.h"  
  2.   
  3. #include<fcntl.h>  
  4.   
  5.    
  6.   
  7. intmain(int argc,char* argv[])  
  8.   
  9. {  
  10.   
  11.         if(argc!=2)  
  12.   
  13.           err_quit("usage:a.out<pathname>");  
  14.   
  15.    
  16.   
  17.         if(access(argv[1],R_OK)<0)  
  18.   
  19.            err_ret("access error for%s",argv[1]);  
  20.   
  21.         else  
  22.   
  23.            printf("read accessok\n");  
  24.   
  25.         if(open(argv[1],O_RDONLY)<0)  
  26.   
  27.           err_ret("open error for%s",argv[1]);  
  28.   
  29.         else  
  30.   
  31.           printf("open for readingok\n");  
  32.   
  33.         exit(0);  
  34.   
  35.    
  36.   
  37. }  


 

运行结果: 

                             


原创粉丝点击