access and faccessat Functions

之前我们说过,打开文件时,内核会根据effective user Id and group ID进行访问权限测试。有时候,进程想使用real user and group ID进行测试。当进程使用set user IDbit和set-group IDbit的时候这是很有用的。即使进程的可能被set-user-ID作为root权限,该进程还是想确定(verify)真实的用户能否访问指定的文件。
accessfaccessat就是基于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.
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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猎羽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值