代码之家  ›  专栏  ›  技术社区  ›  Georg Schölly Crazy Developer

stat()是如何工作的?

  •  1
  • Georg Schölly Crazy Developer  · 技术社区  · 16 年前

    stattest.c:

    // compile: gcc -o stattest stattest.c
    #include <stdio.h>
    #include <sys/stat.h>
    
    int main(int argc, char *argv[]) {
        struct stat stats;
        stat(argv[1], &stats);
        printf("%lli\n", (long long)stats.st_dev);
        return 0;
    }
    

    用法:

    stat -f "%r" /dev/disk0
    => 234881024                  (Value that I'm looking for.)
    
    ./teststat /dev/disk0
    =>  44921876
    
    python -c 'import os,sys; print os.stat(sys.argv[1]).st_dev' /dev/disk0
    =>  44921876
    

    stat 命令给了我什么?

    更新1

    提取44921876的主数字得到2,这是 /dev/tty .

    更新2

    在文件系统上指定文件是有效的。(我在这里只使用python,因为它更快。)

    python -c "import sys,os; print os.stat(sys.argv[1]).st_dev" /path/to/file
    => 234881024
    
    1 回复  |  直到 16 年前
        1
  •  4
  •   unwind    16 年前

    试着打印 st_rdev

    struct stat {
       dev_t    st_dev;    /* device inode resides on */
       [ ... snip ... ]
       dev_t    st_rdev;   /* device type, for special file inode */
    };
    

    我认为您打印的字段与%r格式化程序访问的字段不同。您对设备文件所在的设备不感兴趣,但对文件描述的设备感兴趣。

    这些数字至少与你的预测一致 ls dev_t 类型为32位,这使您可以将其打印为 long long 有点可疑。