免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1266 | 回复: 0
打印 上一主题 下一主题

access函数(APUE2 4.7节) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-11-18 22:43 |只看该作者 |倒序浏览
一、access函数:

当用open函数打开一个文件时,内核以进程的有效用户ID和有效组ID为基础执行其访问权限测试。
有时,进程也希望按其实际用户ID和实际组ID来测试其访问能力。例如当一个进程使用设置用户ID或设置组ID特征作为另一个用户(或组)运行时,就可能会有这种需要。即使一个进程可能已经因设置用户ID以超级用户权限运行,它仍可能想验证其实际用户能否访问一个给定的文件。access函数是按实际用户ID和实际组ID进行访问权限测试的。

函数原型:

#include unistd.h>
int access(const char *pathname, int mode);
                                        Returns: 0 if OK, 1 on error
其中:mode是按照下表所列常量的按位或。
mode
说明
R_OK
测试读权限
W_OK
测试写权限
X_OK
测试执行权限
F_OK
测试文件是否存在

二、举例说明access使用实际用户ID和实际组ID。
实例代码:
#include stdio.h>
#include stdlib.h>
#include fcntl.h>
#include unistd.h>
int main(int argc, char *argv[])
{
        if (argc != 2) {
                printf("usage: %s \n", argv[0]);
                exit(1);
        }
        if (access(argv[1], R_OK)  0)
                printf("access error for: %s: %m\n", argv[1]);
        else
                printf("read access OK\n");
        if (open(argv[1], O_RDONLY)  0)
                printf("open error for: %s: %m\n", argv[1]);
        else
                printf("open for reading OK\n");
        exit(0);
}
下面是该程序的示例会话:(编译为可执行文件:m)
[liumin@localhost access_open]$ ls -l m
-rwxrwxr-x 1 liumin liumin 5514 2009-11-18 23:09 m
[liumin@localhost access_open]$ ./m m
read access OK
open for reading OK
[liumin@localhost access_open]$ ls -l /etc/shadow
-r-------- 1 root root 1206 2009-11-04 21:56 /etc/shadow
[liumin@localhost access_open]$ ./m /etc/shadow
access error for: /etc/shadow: Permission denied
open error for: /etc/shadow: Permission denied
[liumin@localhost access_open]$ su                  成为超级用户
Password:                                            
[root@localhost access_open]# chown root m          将文件用户ID改为root
[root@localhost access_open]# chmod u+s m           打开设置用户ID位
[root@localhost access_open]# ls -l m
-rwsrwxr-x 1 root liumin 5514 2009-11-18 23:09 m
[root@localhost access_open]# exit                  回复为正常用户
exit                                 
[liumin@localhost access_open]$ ./m /etc/shadow
access error for: /etc/shadow: Permission denied
open for reading OK
在本例中,设置用户ID程序可以确定实际用户不能读某个指定文件,而open函数却能打开该文件。

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/105349/showart_2097876.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP