In C on Unix, how can a process tell what permissions it has to a file without opening it?

与世无争的帅哥 提交于 2019-12-08 05:23:11

问题


I can use stat() to figure out what permissions the owner, group, or others have and I can use geteuid() and getpwuid() to get the user name of the process. I'm not quite sure how to get the groups a user belongs to without a system call though.

Even knowing how to get the groups, it seems like a lot of work to integrate all of this information. Is there an easier way?


回答1:


The access() POSIX function can check the permissions without opening it. However, it needs to a syscall.

The access() function shall check the file named by the pathname pointed to by the path argument for accessibility according to the bit pattern contained in amode, using the real user ID in place of the effective user ID and the real group ID in place of the effective group ID.

For example:

access("/etc/passwd",W_OK)

checks if you have write access to the passwd file. With R_OK, read permissions are checked.

The eaccess() function (euidaccess is a synonym) uses the effective user and group id. While eaccess seems to be widely supported, as far as I know it is not part of the POSIX standard.




回答2:


unistd.h defines an access() function,

int access(const char *path, int amode);

where path is your filename and amode is a bitwise inclusive OR of access permissions to check against.

R_OK, W_OK, and X_OK hold mode values for checking read, write, and search/execute permissions respectively.

int readable, readwritable;

//checking for read access
readable = access("/usr/bin/file", R_OK);

//checking for read and write access
readwritable = access("/usr/bin/file", R_OK|W_OK);

You can find a full description of access() in the unix man pages.




回答3:


The acccess() checks the file name pointed by the path argument. The drawback here is each file permission has to be chekced individually using the flags below. R_OK Test for read permission. W_OK Test for write permission. X_OK Test for execute or search permission. F_OK Check existence of file



来源:https://stackoverflow.com/questions/1138508/in-c-on-unix-how-can-a-process-tell-what-permissions-it-has-to-a-file-without-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!