繁体   English   中英

如何在 Linux 驱动程序中获取文件的次要编号?

[英]How to get the minor number of a file in a Linux driver?

有没有更好的解决方案来获取次要号码?

我可以避免检查 kernel 版本吗?

static long unlocked_ioctl(struct file *f, unsigned int o, unsigned long d)
{
#if KERNEL_VERSION(3, 18, 0) > LINUX_VERSION_CODE
    struct inode* inode = f->f_dentry->d_inode;
#else
    struct inode* inode = f->f_path.dentry->d_inode;
#endif

    int minor = iminor(inode);
}

作为 Marco Bonelli 答案的附录,在 3.9 kernel 中添加了file_inode() ,因此如果需要支持更早的 kernel 版本,则需要添加一些 Z50484C19F1AFDAF3841A0D821ED3 兼容性代码。 我使用如下内容:

/*
 * The file_dentry() inline function was added in kernel version 4.6.0.
 * Emulate it for earlier kernels.
 */
#if LINUX_VERSION_CODE < KERNEL_VERSION(4,6,0)
static inline struct dentry *kcompat_file_dentry(const struct file *f)
{
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20)
    return f->f_dentry;
#else
    return f->f_path.dentry;
#endif
}
#undef file_dentry
#define file_dentry(f) kcompat_file_dentry(f)
#endif

/*
 * The file_inode() inline function was added in kernel 3.9.0.
 * Emulate it for earlier kernels.
 */
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,9,0)
static inline struct inode *kcompat_file_inode(struct file *f)
{
    return file_dentry(f)->d_inode;
}
#undef file_inode
#define file_inode(f)   kcompat_file_inode(f)
#endif

是的,有一个更好的方法:当你想要的东西作为struct file的一个字段就在那里时,不要费心去查看dentry

struct file {
    union {
        struct llist_node   fu_llist;
        struct rcu_head     fu_rcuhead;
    } f_u;
    struct path     f_path;
    struct inode    *f_inode; // <-- here's your inode
    // ...
}

您可以直接访问f->f_inode或使用file_inode() function,这样您也可以避免 kernel 版本检查。

static long unlocked_ioctl(struct file *f, unsigned int o, unsigned long d)
{
    int minor = iminor(file_inode(f));
    // ...
}

暂无
暂无

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

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