[comp.unix.questions] How do I read an inode?

jik@athena.mit.edu (Jonathan I. Kamens) (07/27/90)

  (Note the Followup-To and cross-post on this; I don't really think
it's a wizard-level question.)

In article <114837@linus.mitre.org>, oking@smiley.arpa (Osborne I King)
writes:
|> How do I read inode information associated with
|> a special file for example: a block special file.

  Your subject line says, "How do I read an inode?" and your message
says, "How do I read inode information associated with a special
file..." but I'm still not sure what you're asking.

  What "inode information" are you asking about?  Since you mention
special files in particular, my best guess is that you're talking about
the major and minor device numbers and the device type.  To obtain both
of these, you use the stat() system call, the same way you would to
obtain file information about any regular file.

  In particular, the st_mode field of the stat structure tells you
whether it's a character or block special device (S_IFCHR and S_IFBLK on
BSD, I don't know what it is on others), and the st_rdev field tells you
the major and minor device numbers (the first two bytes are the major
number, and the second two bytes are the minor number).

  If that isn't what you're talking about, please explain a little bit
more clearly what you *are* talking about, so we can help you :-).

Jonathan Kamens			              USnail:
MIT Project Athena				11 Ashford Terrace
jik@Athena.MIT.EDU				Allston, MA  02134
Office: 617-253-8495			      Home: 617-782-0710

guy@auspex.auspex.com (Guy Harris) (07/29/90)

>  In particular, the st_mode field of the stat structure tells you
>whether it's a character or block special device (S_IFCHR and S_IFBLK on
>BSD, I don't know what it is on others),

It's the same on others.  WARNING: S_IFCHR, S_IFBLK, and the like are
*NOT* bit flags (you probably already knew this, but plenty of other
folks seem to to); they are bit-field values.  Do *not* test whether
something is a character special file by doing

	if (statb.st_mode & S_IFCHR)

The correct test in UNIX is

	if ((statb.st_mode & S_IFMT) == S_IFCHR)

or, if you have a POSIX-compliant system,

	if (S_ISCHR(statb.st_mode))

>and the st_rdev field tells you the major and minor device numbers (the
>first two bytes are the major number, and the second two bytes are the
>minor number).

You must have System V Release 4. :-)  S5R4 was going to (and I think it
did) expand a "dev_t" to 32 bits; other UNIX systems have 16-bit
"dev_t"s - the first two bytes are the *only* two bytes.  The upper
byte is the major number, and the lower byte is the minor number.

The *right* way to get the major and minor device numbers out of a
"dev_t" such as "st_rdev" is to use the "major()" and "minor()" macros,
found in <sys/types.h> on some systems and <sys/sysmacros.h> on others. 
This insulates you from changes like the ones made in S5R4.