简体   繁体   English

Linux内核中的major()和minor()函数

[英]major() and minor() function in linux kernel

Hi I'm running vfs_stat , fd is an opened file desciptor of /dev/tty0 : 嗨,我正在运行vfs_statfd/dev/tty0的打开的文件描述符:

set_fs (KERNEL_DS);
if (vfs_fstat (fd, &stat))
{
    goto out3;
}

if (stat.mode & S_IFCHR)
    printk (KERN_INFO "opening %s (dev %d)\n", filename, stat.rdev);

And it prints: 它打印:

[ 8657.480625] opening /dev/tty0 (dev 4194304)

So now I need to retrieve major number of the device, but I couldn't find major() or minor() definition in linux kernel. 所以现在我需要检索设备的主设备号,但是在Linux内核中找不到major()minor()定义。

I found this answer but it doesn't seem to be right: 我找到了这个答案,但似乎并不正确:

#define major(dev) ((int)(((unsigned int) (dev) >> 8) & 0xff))
#define minor(dev) ((int)((dev) & 0xff))

Because if I do printk (KERN_INFO "opening %s (dev %d)\\n", filename, major (stat.rdev)); 因为如果执行printk (KERN_INFO "opening %s (dev %d)\\n", filename, major (stat.rdev)); The second field is always zero. 第二个字段始终为零。

How should I get the major number then? 那我应该怎么获得专业号码呢?

I found linux/include/linux/kdev_t.h which has: 我发现linux / include / linux / kdev_t.h具有:

#define MINORBITS        20
#define MINORMASK        ((1U << MINORBITS) - 1)

#define MAJOR(dev)        ((unsigned int) ((dev) >> MINORBITS))
#define MINOR(dev)        ((unsigned int) ((dev) & MINORMASK))
#define MKDEV(ma,mi)      (((ma) << MINORBITS) | (mi))

Which seems "better" than the code you showed, since this has more bits allocated for the major number (20 rather than 8). 这似乎比您显示的代码“更好”,因为它为主要数字分配了更多的位(20而不是8)。

On recent glibc and kernels, you should include sys/sysmacros.h and not only sys/types.h. 在最新的glibc和内核上,您应该包括sys / sysmacros.h,而不仅仅是sys / types.h。 Here is the comment that describe this decision: 这是描述此决定的评论:

/* BSD defines `major', `minor', and `makedev' in this header.
   However, these symbols are likely to collide with user code, so we are
   going to stop defining them here in an upcoming release.  Code that needs
   these macros should include <sys/sysmacros.h> directly.  Code that does
   not need these macros should #undef them after including this header.  */
# define __SYSMACROS_DEPRECATED_INCLUSION
# include <sys/sysmacros.h>
# undef __SYSMACROS_DEPRECATED_INCLUSION

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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