access和faccessat函数是按实际用户ID和实际组ID进行访问权限测试的。
#include <unistd.h>
int access(const char *pathname, int mode);
int faccessat(int fd, const char *pathname, int mode, int flag);
实例:
显示了access函数的使用方法。
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("usage : access <pathname>");
exit(1);
}
if (access(argv[1], R_OK) < 0)
{
printf("access error for %s", argv[1]);
}
else
{
printf("read access OK\n");
}
if (open(argv[1], O_RDONLY) < 0)
{
printf("open error for %s", argv[1]);
}
else
{
printf("open for reading OK\n");
}
exit(0);
}
下面是该程序的示例会话(我编辑的时候将执行文件名改成了access):
$ ls -l a.out
-rwxrwxr-x 1 amy amy 8808 3月 21 20:46 a.out
$ ./a.out a.out
read access OK
open for reading OK
$ ls -l /etc/shadow
-rw-r----- 1 root shadow 1394 10月 19 10:41 /etc/shadow
$ access /etc/shadow
$ su 成为超级用户
Password: 输入超级用户口令
# chown root a.out 将文件用户ID改为root
# chmod u+s a.out 并打开设置用户ID位
# ls -l a.out 检查所有者和SUID位
...............................
# exit 恢复为正常用户
在本例中,尽管open函数能打开文件,但通过设置用户ID程序可以确定实际用户不能正常读指定的文件。