Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use stat function and stat command in Linux system

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to use stat functions and stat commands in the Linux system. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Stat function and stat command

[inode = index node] in the linux file explains: to understand inode, you must understand the disk and [directory items]. Inode is actually the intermediate substance that connects [directory items] and disk.

The big circle in the picture represents the hardware disk, and the small circle in it represents that a file is stored on the disk.

The node of [inode = index node] (the structure that carries node information is: stat,stat is defined later) contains:

File size

The last modification time of the file

The user to which the file belongs

Permissions for the file

Hard link count (numbers displayed by ls-l)

Block location: specifies the specific location where the file is stored on disk.

The hello in the following figure is a normal file, and hello.hard is a hard link to hello.

What is placed in the folder is the [directory entry] of each file, as shown below, and the [directory entry] contains:

File name

The size of the directory entry

Type of file

Inode

How do I view the [inode] of the file? Use the [- I] option

?

one

Ls-li file name

Execution result:

Ys@ys-VirtualBox:~/lianxi1 $ls-li hello hello.hard

3801352-rw-rw-r-- 2 ys ys April 24 11:01 hello

3801352-rw-rw-r-- 2 ys ys April 24 11:01 hello.hard

It is found that the inode (3801352) of hello and hello.hard are the same, which means that only one copy is saved on disk.

How do I view the catalog items? Open the directory (lianxi1) with emacs or vim. The screenshot is as follows. But the [inode] of the file is not seen.

1Maginstat function: gets the file attributes of the specified file, which are stored in the structure stat.

?

one

two

three

four

five

six

seven

# include

# include

# include

Int stat (const char * pathname, struct stat * statbuf)

Int fstat (int fd, struct stat * statbuf)

Int lstat (const char * pathname, struct stat * statbuf)

Struct stat structure:

?

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

Struct stat {

Dev_t st_dev; / * ID of device containing file * /

Ino_t st_ino; / * Inode number * /

Mode_t st_mode; / * File type and mode * /

Nlink_t st_nlink; / * Number of hard links * /

Uid_t st_uid; / * User ID of owner * /

Gid_t st_gid; / * Group ID of owner * /

Dev_t st_rdev; / * Device ID (if special file) * /

Off_t st_size; / * Total size, in bytes * /

Blksize_t st_blksize; / * Block size for filesystem Imax O * /

Blkcnt_t st_blocks; / * Number of 512B blocks allocated * /

/ * Since Linux 2.6, the kernel supports nanosecond

Precision for the following timestamp fields.

For the details before Linux 2.6, see NOTES. , /

Struct timespec st_atim; / * Time of last access * /

Struct timespec st_mtim; / * Time of last modification * /

Struct timespec st_ctim; / * Time of last status change * /

# define st_atime st_atim.tv_sec / * Backward compatibility * /

# define st_mtime st_mtim.tv_sec

# define st_ctime st_ctim.tv_sec

}

St_dev: device ID, less commonly used

St_ino: what is [inode], [inode]? I don't know. Just look at the explanation of [inode] above.

St_mode: file type and permissions, a total of 16 bits, as shown in the following figure.

0-11 bits control the permissions of the file

Types of 12-15 bit control files

0-2 bits: other user permissions

3-5 bits: group user permissions

6-8 bits: this user right

9-11 bits: special permissions

12-15 bits: file type (because there are only 7 file types, 12-14 bits will suffice

The macros of the file type are as follows (the following number is octal):

S_IFSOCK 0140000 socket

S_IFLNK 0120000 symbolic link (soft connection)

S_IFREG 0100000 regular file (normal file)

S_IFBLK 0060000 block device (Block device File)

S_IFDIR 0040000 directory (Catalog)

S_IFCHR 0020000 character device (character device file)

S_IFIFO 0010000 FIFO (Piping)

?

one

two

three

four

five

six

seven

eight

Function that determines the file type and returns true,false

S_ISREG (stat.st_mode) is it a regular file?

S_ISDIR (stat.st_mode) directory?

S_ISCHR (stat.st_mode) character device?

S_ISBLK (stat.st_mode) block device?

S_ISFIFO (m) FIFO (named pipe)?

S_ISLNK (stat.st_mode) symbolic link? (Not in POSIX.1-1996)

S_ISSOCK (stat.st_mode) socket? (Not in POSIX.1-1996)

The macros of file permissions are as follows:

?

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

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: hard connection count

St_uid: the ID of the user to which this file belongs

St_gid: the group ID of the user to which this file belongs

St_rdev: ID for special equipment, which is not commonly used

St_size: the size of the file

St_blksize: I don't know what it is

St_blocks: I don't know what it is

Struct timespec st_atim: time of last visit

Struct timespec st_mtim: when it was last modified

Struct timespec st_ctim: time of last state change

?

one

two

three

four

five

six

seven

Struct timespec {

_ _ kernel_time_t tv_sec; / * seconds * / seconds from the current time to 1970.1.1 00:00:00

Long tv_nsec; / * nanoseconds * / / nanoseconds (I don't know where to go from)

}

1s second = 1000ms millisecond

1ms milliseconds = 1000us microseconds

1us microseconds = 1000ns nanoseconds

Pathname: file name

Return value: 0: success;-1: failure, and set error

Example: statbuf is the structure stat, and you can see that st_mode is a decimal number.

St_mode

Using gdb to display st_mode, it is found that the returned st_mode is a decimal number, which is converted into octal [0100664] with gdb's command [pplink] (o stands for octal). The first 0 stylus is octal, and the last three bits represent file types. The last three digits [664] represent the permissions of this file (this user: rw-, group user: rw-, other users: rmuri -). So you can know the file type and permission settings from st_mode (only 16 bits are used, which is really good to save space, awesome! )

St_uid

St_gid

It is found that st_uid and st_gid are 1000, but how does this 1000 correspond to the user? look at the / etc/passwd file and find that both uid and gid for ys are 1000, so they correspond.

The stat command corresponds to the stat function. The execution result is as follows:

?

one

two

three

four

five

six

seven

eight

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 Uid) Uid: (1000 / ys) Gid: (1000 / ys)

Access: 2019-04-24 1714 02purl 39.199461489 + 0800

Modify: 2019-04-24 16.407461489 + 0800

Change: 2019-04-24 1715 0315 44.927461489 + 0800

2getpwuid function: returns the line of the specified uid in the / etc/passwd file, and puts the information of this line into the structure passwd. Although the return value is a pointer, there is no need to call the free function.

?

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

# include

# include

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 * /

}

3Getgrgid function: returns the line of the specified gid in the / etc/group file, and puts the information of this line into the structure group. Although the return value is a pointer, there is no need to call the free function.

?

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

# include

# include

Struct group * getgrnam (const char * name)

Struct group * getgrgid (gid_t gid)

Struct group {

Char * gr_name; / * group name * /

Char * gr_passwd; / * group password * /

Gid_t gr_gid; / * group ID * /

Char * * gr_mem; / * NULL-terminated array of pointers

To names of group members * /

}

4Maginal localtime function: pass the st_mtim.tv_sec obtained from the stat function (the number of seconds from the current time to 1970.1.1 00:00:00) to get the structure tm. Although the return value is a pointer, there is no need to call the free function.

?

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

# include

Struct tm * localtime (const time_t * timep)

Struct tm {

Int tm_sec; / * Seconds (0-60) * /

Int tm_min; / * Minutes (0-59) * /

Int tm_hour; / * Hours (0-23) * /

Int tm_mday; / * Day of the month (1-31) * /

Int tm_mon; / * Month (0-11) * /

Int tm_year; / * Year-1900 * /

Int tm_wday; / * Day of the week (0-6, Sunday = 0) * /

Int tm_yday; / * Day in the year (0-365,1 Jan = 0) * /

Int tm_isdst; / * Daylight saving time * /

}

5 stat lstat function: when stat encounters a soft link, it will trace back to the source file and penetrate; lstat will not penetrate.

Example: imitating ls-l file

?

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

twenty-six

twenty-seven

twenty-eight

twenty-nine

thirty

thirty-one

thirty-two

thirty-three

thirty-four

thirty-five

thirty-six

thirty-seven

thirty-eight

thirty-nine

forty

forty-one

forty-two

forty-three

forty-four

forty-five

forty-six

forty-seven

forty-eight

forty-nine

fifty

fifty-one

fifty-two

fifty-three

fifty-four

fifty-five

# include

# include

# include

# include

# include

# include / / getpwuid

# include

# include / / localtime

# include / / getgrgid

Int main (int argc, char* argv []) {

Struct stat sbuf

/ / stat (argv [1], & sbuf)

Lstat (argv [1], & sbuf)

Char str [11] = {0}

Memset (str,'-', (sizeof str-1))

/ / File type

If (S_ISREG (sbuf.st_mode)) str [0] ='-'

If (S_ISDIR (sbuf.st_mode)) str [0] ='d'

If (S_ISCHR (sbuf.st_mode)) str [0] ='c'

If (S_ISBLK (sbuf.st_mode)) str [0] ='b'

If (S_ISFIFO (sbuf.st_mode)) str [0] ='p'

If (S_ISLNK (sbuf.st_mode)) str [0] ='l'

If (S_ISSOCK (sbuf.st_mode)) str [0] ='s'

/ / File permissions of this user

If (sbuf.st_mode & S_IRUSR) str [1] ='r'

If (sbuf.st_mode & S_IWUSR) str [2] ='w'

If (sbuf.st_mode & S_IXUSR) str [3] ='x'

/ / File permissions of this user's group

If (sbuf.st_mode & S_IRGRP) str [4] ='r'

If (sbuf.st_mode & S_IWGRP) str [5] ='w'

If (sbuf.st_mode & S_IXGRP) str [6] ='x'

/ / File permissions of other users

If (sbuf.st_mode & S_IROTH) str [7] ='r'

If (sbuf.st_mode & S_IWOTH) str [8] ='w'

If (sbuf.st_mode & S_IXOTH) str [9] ='x'

Char ymd [20] = {0}

/ / date and time of acquisition

Struct tm* tm = localtime (& sbuf.st_atim.tv_sec)

Sprintf (ymd, "2d month 2d d tm_mon d", tm- > tm_mon + 1, tm- > tm_mday

Tm- > tm_hour + 1 tm_hour TM-> tm_sec)

/ /-rw-r--r-- 1 ys ys 134 April 25 09:21 st2.c

Printf ("% s% ld% s% s% ld% s% s\ n", str, sbuf.st_nlink

Getpwuid (sbuf.st_uid)-> pw_name, getgrgid (sbuf.st_gid)-> gr_name

Sbuf.st_size, ymd, argv [1])

Return 0

}

6Query access function: judge the user's permission to the specified file (readable? Writable? Executable? )

?

one

two

# include

Int access (const char * pathname, int mode)

Example:

?

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

# include

# include / / access

Int main (int argc, char* argv []) {

If (access (argv [1], R_OK) = = 0)

Printf ("read ok\ n")

If (access (argv [1], W_OK) = = 0)

Printf ("write ok\ n")

If (access (argv [1], X_OK) = = 0)

Printf ("exe ok\ n")

If (access (argv [1], F_OK) = = 0)

Printf ("exists\ n")

}

First use ls-l to view the permissions of the / usr/include/time.h file, and the results are as follows

?

one

two

Ys@ys-VirtualBox:~/lianxi$ ls-l / usr/include/time.h

-rw-r--r-- 1 root root 10360 April 17 2018 / usr/include/time.h

Use the ys user to execute the example program and view the / usr/include/time.h file. The results are as follows. Because time.h belongs to the root user, for other users, it is [Rmura -], so the following results are obtained.

?

one

two

three

Ys@ys-VirtualBox:~/lianxi$. / ac / usr/include/time.h

Read ok

Exists

Still execute with the ys user, but add sudo, and the result is as follows. The result is the same as that of the root user. Because of the addition of sudo, root users are programmed.

?

one

two

three

four

five

Ys@ys-VirtualBox:~/lianxi$ sudo. / ac / usr/include/time.h

[sudo] password for ys:

Read ok

Write ok

Exists

7Gravity truncate function: truncates the file size and extends the file size

?

one

two

three

# include

# include

Int truncate (const char * path, off_t length)

Path: files for

Length:

If the length is larger than the size of the original file, the file size is extended to length

If length is less than the size of the original file, the file size will be truncated to length

8 ~ # link function: create hard links

?

one

two

# include

Int link (const char * oldpath, const char * newpath)

Return value: 0 for success,-1 for failure, and set errno.

9pr symlink function: create soft links

?

one

two

# include

Int symlink (const char * target, const char * linkpath)

Return value: 0 for success,-1 for failure, and set errno.

10 buf Readlink function: find the actual file corresponding to the soft link and put the name of the file in the file. Note: hard links are not good.

?

one

two

# include

Ssize_t readlink (const char * pathname, char * buf, size_t bufsiz)

Return value: the number of bytes written to buf is returned successfully,-1 is returned for failure, and errno is set.

11PowerUnlink function: delete soft and hard links, you can also delete files.

?

one

two

# include

Int unlink (const char * pathname)

Return value: 0 for success,-1 for failure, and set errno.

There is a special use: the following open code wants to create a hello file, and then delete it directly with unlink, but it can be written successfully, the ret is greater than 0, after the program is executed, it is found that it has not been made into a hello file.

Conclusion: when unlink is executed, the count is 0, but it is found that other processes also refer to this file. At this point in time, unlink will not delete the file, and then delete it after the end of the process, so the following write code can be written successfully.

Using this feature can be achieved: when watching video online, the video file is actually downloaded locally (then in the code, use unlink), after watching the video file count is 0, it is automatically deleted, not afraid that the video is leaked.

?

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

# include

# include

# include

# include

# include

Int main () {

Int fd = open ("hello", O_WRONLY | O_CREAT, 0666)

Unlink ("hello")

Int ret = write (fd, "aaa", 4)

If (ret > 0) {

Printf ("write OK\ n")

}

}

12Makedown function: change the users and groups of the file

?

one

two

# include

Int chown (const char * pathname, uid_t owner, gid_t group)

Pathname: files for

Owner: user ID (digital) / etc/passwd

Group: group ID (numeric) / etc/group

Return value: 0 successful,-1 failed.

13dyrename function: rename

?

one

two

# include

Int rename (const char * oldpath, const char * newpath)

Oldpath: the original file name, the latter directory

Newpath: the new file name, the latter directory

Return value: 0 successful,-1 failed.

14recoverygetcwd function: get the directory of the current work

?

one

two

# include

Char * getcwd (char * buf, size_t size)

Buf: current working directory

Size: buffer siz

Return value: successful return of the current working directory failed to return NULL

15Gramchdir function: change the working directory of the process

?

one

two

# include

Int chdir (const char * path)

Path: target working directory

Return value: 0 successful,-1 failed

16pm mkdir function: create a directory

?

one

two

three

# include

# include

Int mkdir (const char * pathname, mode_t mode)

Pathname: target working directory mode:mode & ~ umask & 0777. Note that if you do not have x permission, you cannot cd into this directory. Return value: 0 successful,-1 failed

17th rmdir function: delete the directory, the directory must be empty, that is, there are no files in it.

?

one

two

# include

Int rmdir (const char * pathname)

18pr opendir function: opens a directory

?

one

two

three

# include

# include

DIR * opendir (const char * name)

Name: directory name

Return value: a pointer to the directory stream

19pr readdir function: read the catalog

?

one

two

three

# include

# include

DIR * opendir (const char * name)

The return value of the dirp:opendir function

Return value: structure dirent, which can be understood as [directory item] NULL represents the content of the directory item other than the end of the read or there is an error NULL

20min closures function: close the directory

?

one

two

three

# include

# include

Int closedir (DIR * dirp)

The return value of the dirp:opendir function

21 errno strerron function: print out the corresponding text message.

?

one

two

# include

Char * strerror (int errnum)

The errnum macro is placed in the file: / usr/include/asm-generic/errno.h

Example:

?

one

two

three

four

five

six

seven

# include

# include

# include / / EDEADLK

Int main () {

Char* buf = strerror (EDEADLK)

Printf ("% s\ n", buf); / / Resource deadlock avoided

}

22pr DUP and dup2 functions: redirection of file descriptors

?

one

two

three

# include

Int dup (int oldfd)

Int dup2 (int oldfd, int newfd)

Dup: similar to open, first open a new file descriptor so that the new file descriptor also points to the place where oldfd points. Successfully returns the newly opened file descriptor; failure returns-1.

Dup2: first eliminate the direction of newfd and then let newfd point to the place where oldfd points to successfully return newfd; failure return-1.

Example: call printf2 several times, the first time printf writes the content to the file; the second time printf prints the content to the screen.

?

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

# include

# include

# include

# include

# include

Int main () {

Int oldfd = dup (STDOUT_FILENO)

Int fd = open ("www", O_WRONLY | O_CREAT, 0666)

Dup2 (fd, STDOUT_FILENO)

Printf ("aaaa\ n")

Fflush (stdout)

Int ret = dup2 (oldfd, STDOUT_FILENO)

/ / int ret = dup2 (oldfd, 6)

/ / perror ("dup2:")

Printf ("reg:%d\ n", ret)

Printf ("aaaa\ n")

Close (fd)

}

On how to use stat functions and stat commands in the Linux system to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Original link: https://www.cnblogs.com/xiaoshiwang/p/10764243.html

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report