之前我们说过,打开文件时,内核会根据effective user Id and group ID
进行访问权限测试。有时候,进程想使用real user and group ID
进行测试。当进程使用set user ID
bit和set-group ID
bit的时候这是很有用的。即使进程的可能被set-user-ID作为root
权限,该进程还是想确定(verify)真实的用户能否访问指定的文件。
access
和faccessat
就是基于real userID and group ID
的。
#include <unistd.h>
int access(const char *pathname, int mode);
#include <fcntl.h> /* Definition of AT_* constants */
#include <unistd.h>
int faccessat(int dirfd, const char *pathname, int mode, int flags);
//Returns: both 0 if OK, -1 on error
The mode is either the value F_OK to test if a file exists, or the bitwise OR(按位与) of any of the flags shown in Figure 4.7.
The faccessat function behaves like access when the pathname argument is absolute(绝对路径) or when the fd argument has the value AT_FDCWD and the pathname argument is relative.
Otherwise, faccessat evaluates(评价) the pathname relative to the open directory referenced by the fd argument(路径为相对于fd目录的相对路径).
Theflag
argument can be used to change the behavior of faccessat
. If the AT_EACCESS
flag is set, the access checks are made using the effective user and group IDs of the calling process instead of the real user and group IDs.
Example
以下实例演示了如何使用access
先通过access确定文件是否具有read
权限,再用只读方式open
文件。
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
if(argc != 2)
{
fprintf(stderr, "usage: access <pathname>\n");
exit(-1);
}
if(access(argv[1], R_OK) < 0)
{
fprintf(stderr, "File %s don't have read permission\n", argv[1]);
exit(-1);
}
else
{
printf("%s can read\n", argv[1]);
}
if(open(argv[1], O_RDONLY) < 0)
{
fprintf(stderr, "open %s error\n", argv[1]);
exit(-1);
}
else
{
printf("open file %s for read\n", argv[1]);
}
return 0;
}
In this example, the set-user-ID
program can determine that the real user cannot normally read the file, even though the open function will succeed.