Linux stat函数和stat命令(2)

文件权限的宏如下:

S_ISUID 04000 set-user-ID bit S_ISGID 02000 set-group-ID bit (see below) S_ISVTX 01000 sticky bit (see below) S_IRWXU 00700 owner has read, write, and execute permission S_IRUSR 00400 owner has read permission S_IWUSR 00200 owner has write permission S_IXUSR 00100 owner has execute permission S_IRWXG 00070 group has read, write, and execute permission S_IRGRP 00040 group has read permission S_IWGRP 00020 group has write permission S_IXGRP 00010 group has execute permission S_IRWXO 00007 others (not in group) have read, write, and execute permission S_IROTH 00004 others have read permission S_IWOTH 00002 others have write permission S_IXOTH 00001 others have execute permission

st_nlink:硬连接计数

st_uid:这个文件所属用户的ID

st_gid:这个文件所属用户的组ID

st_rdev:特殊设备的ID,不太常用

st_size:文件的大小

st_blksize:不明是干啥的

st_blocks:不明是干啥的

struct timespec st_atim:最后访问的时间

struct timespec st_mtim:最后修改的时间

struct timespec st_ctim:最后状态改变的时间

struct timespec { __kernel_time_t tv_sec; /* seconds */当前时间到1970.1.1 00:00:00的秒数 long tv_nsec; /* nanoseconds *//纳秒数(不知道从哪到哪的) }; 1s 秒 = 1000ms 毫秒 1ms 毫秒 = 1000us 微秒 1us 微秒 = 1000ns 纳秒

pathname:文件名

返回值:0代表成功;-1代表失败,并设置error

例子:statbuf是结构体stat,可以看出来st_mode是个10进制的数字。

Linux stat函数和stat命令

st_mode

用gdb显示st_mode,发现返回的st_mode是个10进制的数字,用gdb的【p/o】(o代表用8进制表示)命令把10进制的33204转换成了8进制的【0100664】,第一个0代笔是8进制,后三位的【100】代表文件类型,从上面的说明可以看出来【100】代表普通文件,最后三位的【664】代表这个文件的权限(本用户:rw-,组用户:rw-,其他用户:r--)。所以从st_mode里就可以得知文件的类型和权限设置(只使用了16个比特位,真的好节省空间,牛逼!)

st_uid

st_gid

发现st_uid和st_gid是1000,但这个1000怎么和用户对应上呢,查看/etc/passwd文件,发现用于ys的uid和gid都是1000,所以就对应上了。

Linux stat函数和stat命令

stat命令,是stat函数对应,执行结果如下:

ys@ys-VirtualBox:~/lianxi1$ stat hello File: hello Size: 11 Blocks: 8 IO Block: 4096 regular file Device: 801h/2049d Inode: 3801352 Links: 2 Access: (0764/-rwxrw-r--) Uid: ( 1000/ ys) Gid: ( 1000/ ys) Access: 2019-04-24 17:02:39.199461489 +0800 Modify: 2019-04-24 16:54:16.407461489 +0800 Change: 2019-04-24 17:03:44.927461489 +0800

2,getpwuid函数:返回/etc/passwd文件里指定uid的行,把这一行的信息放入结构体passwd中。虽然返回值是指针,但不需要调用free函数。

#include <sys/types.h> #include <pwd.h> struct passwd *getpwnam(const char *name); struct passwd *getpwuid(uid_t uid); struct passwd { char *pw_name; /* username */ char *pw_passwd; /* user password */ uid_t pw_uid; /* user ID */ gid_t pw_gid; /* group ID */ char *pw_gecos; /* user information */ char *pw_dir; /* home directory */ char *pw_shell; /* shell program */ };

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/cece8045ebccfb7b6acd45f696ad5274.html