Day02_access函数文件访问权限测试
::::::::::
/*
access()函数,文件访问权限测试,
能测试这个进程是否有权限访问这个文件。
access函数原型:
::::::::::::
access - check real user鈥檚permissions for a file
SYNOPSIS
#include <unistd.h>
int access(const char *pathname, int mode);
DESCRIPTION
access() checks whether the calling process can access the filepathname. If pathname is a symboliclink, it is dereferenced.
The mode specifies the accessibility check(s) to beperformed, and is either the value F_OK, or a mask consisting of the bitwise ORof one or more of R_OK, W_OK, and
X_OK. F_OK tests for theexistence of the file. R_OK, W_OK, andX_OK test whether the file exists and grants read, write, and executepermissions, respectively.
The check is done using the calling process鈥檚 real UIDand GID, rather than the effective IDs as is done when actually attempting anoperation (e.g., open(2)) on the
file. This allows set-user-IDprograms to easily determine the invoking user鈥檚 authority.
If the calling process is privileged (i.e., its real UID is zero), then an X_OK checkis successful for a regular file if execute permission is enabled for any ofthe
file owner, group, or other.
RETURN VALUE
On success (all requested permissions granted), zero is returned. On error (at least one bit in mode askedfor a permission that is denied, or some other error
occurred), -1 is returned, and errno is set appropriately.
ERRORS
access() shall fail if:
EACCES The requested access wouldbe denied to the file, or search permission is denied for one of thedirectories in the path prefix of pathname. (See also path_reso-
lution(7).)
ELOOP Too many symbolic linkswere encountered in resolving pathname.
ENAMETOOLONG
pathname is too long.
ENOENT A component of pathname does not exist or is a dangling symboliclink.
ENOTDIR
A component used as a directoryin pathname is not, in fact, a directory.
EROFS Write permission wasrequested for a file on a read-only file system.
access() may fail if:
EFAULT pathname points outside your accessible address space.
EINVAL mode was incorrectly specified.
EIO An I/O error occurred.
ENOMEM Insufficient kernel memory was available
:::::::::::::::::::::
*/
测试实例源代码:
用该进程创建一个my.txt 文件,然后用access()函数测试。
程序源代码:
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<error.h>
#include<errno.h>
int main()
{
int access_returnvalue ;
access_returnvalue=access("/home/code/file1/my.txt",R_OK);
if(access_returnvalue!=-1)
printf("theaccessiblity of reading is not ok\n");
printf("theread accessibility is :%d\n",access_returnvalue);
access_returnvalue=access("/home/code/file1/my.txt",W_OK);
if(access_returnvalue!=-1)
printf("thewrite is allowed");
printf("THERETURN VALUE IS :%d \n",access_returnvalue);
return 0;
}
程序运行截图: