ls 或 stat 之类的命令如何区分文件类型,对象是文件还是目录?
例如,我创建了这两个对象,考虑到目录也是文件的事实......有一些特殊规则,我想知道在命令的输出中如何将stat它们标记为“目录”和“常规空文件” ”。
$ mkdir testdir;touch testfile
$ stat testdir | head -2;stat testfile | head -2
File: `testdir'
Size: 4096 Blocks: 8 IO Block: 4096 directory
File: `testfile'
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Run Code Online (Sandbox Code Playgroud)
后来,我在分别执行目录testdir和文件testfile的stat时做了一个strace。在跟踪输出中,我注意到这些
lstat("testdir/", {st_mode=S_IFDIR|0775, st_size=4096, ...}) = 0
Run Code Online (Sandbox Code Playgroud)
和
lstat("testfile", {st_mode=S_IFREG|0664, st_size=0, ...}) = 0
Run Code Online (Sandbox Code Playgroud)
有人请告诉我如何st_mode获得这些值S_IFDIR和S_IFREG.
我可能听起来很困惑;我确实是。
让我们试着消除你的困惑。在inodest_mode 中有一个由 stat/lstat(和 64 位变体)返回的 16 位字段。其中 9 位用于 rwxrwxrwx 权限,另外 3 位用于sticky bit,set group id (sgid) bit和set userid (suid) bit. 其他 4 位用于编码一些类型信息。这可以说它是一个普通文件、一个目录、一个块或字符设备、一个命名管道等。
因此,如果您创建一个目录,那么这 4 位表示它是一个目录。您可以在 strace 输出中看到这一点...
lstat("testdir/", {st_mode=S_IFDIR|0775, st_size=4096, ...})
^^^^^^^ 4 bits showing the type is directory
^ 3 bits (this is octal) for suid/sgid/sticky
^^^ rwxrwxrwx info.
Run Code Online (Sandbox Code Playgroud)