Unix:"ls -l" 在哪里获取设备大小字段中的逗号分隔值?

Unix: Where does "ls -l" get comma-separated values in size field for devices?

当我在 OS X 上 运行 ls -l /dev 时,我得到以下格式的输出(但还有更多文件):

crw-rw-rw-  1 root       wheel            4, 126 Jun 11 20:28 ttywe
crw-rw-rw-  1 root       wheel            4, 127 Jun 11 20:28 ttywf

据我所知,它特定于该文件夹,我无法在任何地方找到 4, 的含义。 我正在用 C 重写 ls,所以我想知道它是什么,如果可能的话,如何在 C 中检索该值。

来自 the POSIX specification for ls:

If the file is a character special or block special file, the size of the file may be replaced with implementation-defined information associated with the device in question.

在这种特殊情况下,您几乎肯定有一个打印主要和次要设备编号的实现——这些值将传递给 mknod 以创建指向同一设备的文件。但是, 不需要任何实现来提供此信息,您的 ls 实现可以在没有它的情况下符合标准。


如果您想知道如何在 C 中实现它,一个好的起点是 man 2 statst_rdev 是您在本次调用填写的 struct stat 中关心的字段。在 Linux 上,您可以通过调用宏 MAJOR(stat_result.st_rdev)MINOR(stat_result.st_rdev) 来提取主要和次要编号(假设您告诉 stat 写入名为 stat_result 的结构).