#include
int access(const char *pathname, int mode);
返回值:成功返回0;失败返回-1,设置errno;
access函数中mode参数说明
mode 说明
R_OK 测试读权限
W_OK 测试写权限
X_OK 测试执行权限
F_OK 测试文件是否存在
open打开一个文件,内核以进程的有效用户ID和有效组ID为基础执行其访问权限测试。
access是以实际用户ID和实际组ID为基础来测试其访问能力。
#include
int open(const char *pathname, int flags, mode_t mode);
返回值:成功,返回文件描述符;失败返回-1,设置errno
-
#include <unistd.h>
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <fcntl.h>
-
-
int main(int argc, char *argv[])
-
{
-
int fd;
-
int ret;
-
-
if(argv[1] == NULL) {
-
printf("Usage:./a.out file_name\n");
-
return 0;
-
}
-
-
fd = open(argv[1],O_WRONLY);
-
if(fd < 0) {
-
printf("open error for %s\n",argv[1]);
-
}else {
-
printf("open for writing OK\n");
-
}
-
-
ret = access(argv[1],W_OK);
-
if(ret <0) {
-
printf("access error for %s\n",argv[1]);
-
}else {
-
printf("write access ok\n");
-
}
-
-
return 0;
-
}
编译运行:
gwwu@hz-dev2.wgw.com:~/test/file>-rwxrwxr-x 1 gwwu gwwu 8436 Nov 27 10:45 access
以gwwu用户执行程序,程序的有效用户ID为gwwu,有效组ID也为gwwu
gwwu@hz-dev2.aerohive.com:~/test/file>ls -al
total 60
drwxrwxr-x 2 gwwu gwwu 4096 Nov 27 11:15 .
drwxr-xr-x 21 gwwu gwwu 4096 Nov 24 14:44 ..
-rwxrwxr-x 1 gwwu gwwu 8752 Nov 27 11:15 access
-rw-rw-r-- 1 gwwu gwwu 643 Nov 27 11:15 access.c
-rwxrwxr-x 1 gwwu gwwu 9843 Nov 24 16:49 lstate
-rw-rw-r-- 1 gwwu gwwu 1030 Nov 24 16:49 lstate.c
---------- 1 gwwu gwwu 0 Nov 26 14:33 txy
-rwxrwxr-x 1 gwwu gwwu 9575 Nov 26 16:07 umask
-rw-rw-r-- 1 gwwu gwwu 919 Nov 26 16:07 umask.c
-rw-rw-rw- 1 gwwu gwwu 8 Nov 26 16:07 wgw
gwwu@hz-dev2.wgw.com:~/test/file>./access access
open error for access:Text file busy-----------------------------------注意此处,由于access正在执行的时候判断文件是否可写会出错。
write access ok
gwwu@hz-dev2.wgw.com:~/test/file>./access access.c
open for writing OK
write access ok
gwwu@hz-dev2.aerohive.com:~/test/file>./access lstate
open for writing OK
write access ok
gwwu@hz-dev2.wgw.com:~/test/file>./access /etc/passwd
open error for /etc/passwd:Permission denied
access error for /etc/passwd:Permission denied
gwwu@hz-dev2.wgw.com:~/test/file>ls -al /etc/passwd
-rw-r--r-- 1 root root 2316 Aug 5 16:05 /etc/passwd
write access ok
su进入超级用户,将access的用户ID改成root
chown root access
chmode u+s access
再退出超级用户,
执行./access /etc/passwd
open
open for writing OK
acess error for /etc/passwd
access error for /etc/passwd:Permission denied
阅读(1439) | 评论(0) | 转发(0) |