APUE第三版 程序 4-8(文件访问权限与 access 函数)

如有错误,欢迎批评指正,本人也是才学APUE的菜鸟

先贴上程序代码:

#include "apue.h"
#include <fcntl.h>

int main(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 access OK\n");

	if(open(argv[1], O_RDONLY) < 0)
		err_ret("open error for %s,", argv[1]);
	else
		printf("open for reading OK\n");
}

/
/

该程序是 access 实例,即对 access 函数的使用。access 函数是按实际用户 ID 和实际组 ID 来进行访问权限测试的。

对于 access 的输出,取决于进程的实际用户 ID;对于 open 函数的输出,取决于进程的有效用户 ID

这里是终端的测试过程:

hjm@hjm-Inspiron:~/InterviewPreparation/apue/Examples/4-8$ ls -l 4-8
-rwxr-xr-x 1 hjm hjm 13280 4月  17 19:15 4-8
hjm@hjm-Inspiron:~/InterviewPreparation/apue/Examples/4-8$ ./4-8 4-8
read access OK
open for reading OK
hjm@hjm-Inspiron:~/InterviewPreparation/apue/Examples/4-8$ ls -l /etc/shadow
-rw-r----- 1 root shadow 1393 4月  17 19:21 /etc/shadow
hjm@hjm-Inspiron:~/InterviewPreparation/apue/Examples/4-8$ ./4-8 /etc/shadow
access error for /etc/shadow: Permission denied
open error for /etc/shadow,: Permission denied
hjm@hjm-Inspiron:~/InterviewPreparation/apue/Examples/4-8$ su
密码: 
root@hjm-Inspiron:/home/hjm/InterviewPreparation/apue/Examples/4-8# chown root 4-8
root@hjm-Inspiron:/home/hjm/InterviewPreparation/apue/Examples/4-8# chmod u+s 4-8
root@hjm-Inspiron:/home/hjm/InterviewPreparation/apue/Examples/4-8# ls -l 4-8
-rwsr-xr-x 1 root hjm 13280 4月  17 19:15 4-8
root@hjm-Inspiron:/home/hjm/InterviewPreparation/apue/Examples/4-8# exit
exit
hjm@hjm-Inspiron:~/InterviewPreparation/apue/Examples/4-8$ ./4-8 /etc/shadow
access error for /etc/shadow: Permission denied
open for reading OK
  1. 编译好 4-8.c 文件,形成 4-8,首先查看了该文件的属性。
    -rwxr-xr-x:这是一个普通文件,对其所有者的权限是 r (可读)、w (可写)、x (可执行);对其组所有者的权限是:r、x;对其他用户的权限是 r、x;
    其所有者为 hjm,组所有者为 hjm

  2. 执行命令 ./4-8 4-8
    由输出可知,进程实际用户 ID 对文件 4-8 有可读权限;同时该进程可以成功 open;(此时的有效用户=实际用户)

  3. 然后查看了 /etc/shadow 文件的属性。可以与 1 进行同样的解读。

  4. 执行命令 ./4-8 /etc/shadow
    可知,进程实际用户 ID 对文件 /etc/shadow 没有可读权限,该进程也无法成功 open;(此时的有效用户=实际用户)

  5. 切换到了 root 用户,首先使用了命令 chown 改变了 4-8 的所有者;然后利用 chmod 命令打开了文件模式字(st_mode)中的设置用户 ID 位,其具体含义是,当执行 4-8 时,将用文件所有者作为有效用户。
    再次查看了 4-8 的相关文件属性。
    然后 exit 恢复为正常用户。

  6. 再次利用程序对 /etc/shadow 查看相关权限
    发现,进程实际用户 ID 仍然对此文件没有读权限,但是该进程可以成功打开文件 (因为此时的有效用户为 root)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值