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

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

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

#include<unistd.h> 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

测试读权限

测试写权限

测试执行权限

测试文件是否存在

实例

#include"apue.h" #include<fcntl.h> intmain(int argc,char* argv[]) { if(argc!=2) err_quit("usage:a.out<pathname>"); if(access(argv[1],R_OK)<0) err_ret("access error for%s",argv[1]); else printf("read accessok\n"); if(open(argv[1],O_RDONLY)<0) err_ret("open error for%s",argv[1]); else printf("open for readingok\n"); exit(0); }


运行结果:



更多内容欢迎访问:http://blog.csdn.net/wallwind

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值