简体   繁体   中英

How does stat() work?

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;
}

Usage:

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

Why doesn't my code give me the value the stat command gives me?

Update 1

Extracting the major number of 44921876 gives me 2 which is /dev/tty .

Update 2

Specifying a file on the filesystem works. (I'm only using python here because it's faster.)

python -c "import sys,os; print os.stat(sys.argv[1]).st_dev" /path/to/file
=> 234881024

Try printing the st_rdev member. The manual page says:

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

I think you're not printing the same field that the %r formatter accesses. You're not interested in the device the device file is on, but the device that the file describes.

The numbers are at least consistent with your ls output; major=14 and minor=0, and you print 234881024, which in hex is 0xE000000. 0xE is, of course, 14 decimal. This indicates Mac OS X stores the major number in the top 8 bits, and the minor number in the lower 24. This, in turn, implies that the dev_t type is 32-bit, which makes your printing it as long long a bit dubious.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM