File Stat

2015/06/25

Categories: Unix Program Tags: apue unix

查看文件信息

#include <sys/stat.h>
int fstat(int filedes, struct stat *buf));
int lstat(const char *pathname, struct stat *buf);
int stat(const char *pathname, struct stat *buf);

st_mode,文件模式字。 文件类型(S_IFMT):

S_ISXXX 宏的实现: #define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)

每个文件有 9 个访问权限位:

/* Read, write, execute/search by owner */
#define S_IRWXU 0000700 /* [XSI] RWX mask for owner */
#define S_IRUSR 0000400 /* [XSI] R for owner */
#define S_IWUSR 0000200 /* [XSI] W for owner */
#define S_IXUSR 0000100 /* [XSI] X for owner */
/* Read, write, execute/search by group */
#define S_IRWXG 0000070 /* [XSI] RWX mask for group */
#define S_IRGRP 0000040 /* [XSI] R for group */
#define S_IWGRP 0000020 /* [XSI] W for group */
#define S_IXGRP 0000010 /* [XSI] X for group */
/* Read, write, execute/search by others */
#define S_IRWXO 0000007 /* [XSI] RWX mask for other */
#define S_IROTH 0000004 /* [XSI] R for other */
#define S_IWOTH 0000002 /* [XSI] W for other */
#define S_IXOTH 0000001 /* [XSI] X for other */

目录的读和执行权限是不一样的:读权限允许我们获得该目录下的所有文件名列表,而执行权限则允许我们进入、通过这个目录。

进程每次打开、创建或删除一个文件时,内核就进行文件访问权限测试。

access 函数:访问权限测试函数

#include <unistd.h>
int access(const char *pathname, int mode);

mode 有四种取值:

#define F_OK 0 /* test for existence of file */
#define X_OK (1<<0) /* test for execute or search permission */
#define W_OK (1<<1) /* test for write permission */
#define R_OK (1<<2) /* test for read permission */

umask 函数:权限掩码,设置文件模式创建屏蔽位,即在创建某个文件的时候,屏蔽掉哪些权限。

#include <sys/stat.h>
mode_t umask(mode_t mode);

更改文件的访问权限:

int chmod(const char *pathname, mode_t mode);
int fchmod(int filedes, mode_t mode);