《UNIX环境高级编程》笔记10--access函数

来源:互联网 发布:上海市政务数据资源网 编辑:程序博客网 时间:2024/05/18 00:29

access函数是按照实际用户ID和实际组ID进行访问测试的。函数的定义如下:

[cpp] view plain copy
  1. #include <unistd.h>  
  2. int access(const char* pathname, int mode);  
  3. //若成功返回0,若出错则返回-1.  

其中mode是下面所列常量的按位或。


实践:

[java] view plain copy
  1. #include <unistd.h>  
  2. #include <stdio.h>  
  3. #include <fcntl.h>  
  4.   
  5. int main(void){  
  6.         if(access("a",F_OK|R_OK|W_OK) < 0){  
  7.                 perror("access");  
  8.         }  
  9.   
  10.         int fd = -1;  
  11.         if((fd = open("a",O_RD))<0){  
  12.                 perror("open");  
  13.                 return -1;  
  14.         }  
  15.         printf("open ok!\n");  
  16.   
  17.         return 0;  
  18. }  
运行结果:

yan@yan-vm:~/apue$ ll a

-rwsr--r-- 1 root root 0 Apr 24 23:49 a*

yan@yan-vm:~/apue$ ./a.out

access: Permission denied

open: open ok!

使用yan运行执行access函数,因为a文件属于root,所以没有权限,因为access是使用实际用户ID和实际组ID进行测试的,但是

可以使用open函数以读的方式打开,因为设置了SUID。

注意:如果使用open函数以读写的方式打开,就会出现Permission denied,因为这样会有潜在的问题,如果用户在a中添加了恶意

代码,但是执行a时还是具有root的权限,那就不好了。

原创粉丝点击