linux - 当 kmalloc 已经返回指向内存位置的指针时,为什么需要 container_of?

标签 linux linux-kernel linux-device-driver

kmalloc() 返回一个指向初始化期间分配的内存位置的指针,如果使包含 cdev 的结构指向它,为什么需要在文件操作 open 调用中执行 container_of 以再次获取包含 cdev 的结构的地址?

最佳答案

我猜你指的是这样的东西:

http://www.cs.uni.edu/~diesburg/courses/dd/code/scull/pipe.c

static int scull_p_open(struct inode *inode, struct file *filp)
{
    struct scull_pipe *dev;

    dev = container_of(inode->i_cdev, struct scull_pipe, cdev);
    // ...

kmalloc是这样使用的:

    scull_p_devices = kmalloc(scull_p_nr_devs * sizeof(struct scull_pipe), GFP_KERNEL);

struct scull_pipe 是:

struct scull_pipe {
        wait_queue_head_t inq, outq;       /* read and write queues */
        char *buffer, *end;                /* begin of buf, end of buf */
        int buffersize;                    /* used in pointer arithmetic */
        char *rp, *wp;                     /* where to read, where to write */
        int nreaders, nwriters;            /* number of openings for r/w */
        struct fasync_struct *async_queue; /* asynchronous readers */
        struct semaphore sem;              /* mutual exclusion semaphore */
        struct cdev cdev;                  /* Char device structure */
};

使用 container_of 的原因是在 scull_p_open 回调中你没有指向 struct scull_pipe 实例的指针,但是你可以访问cdev struct scull_pipe 结构的成员(通过inode->i_cdev)。为了得到cdev的容器地址(换句话说就是struct scull_pipe实例的地址),你需要使用container_of:

struct scull_pipe *dev;

dev = container_of(inode->i_cdev, struct scull_pipe, cdev);

关于linux - 当 kmalloc 已经返回指向内存位置的指针时,为什么需要 container_of?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32625775/

相关文章:

linux - 内核驱动程序从用户空间读取正常,但写回始终为 0

linux - linux 中的 Probe() 方法是否需要重入?

html - 没有这样的文件或目录 : var/www/html in ec2 instance

mysql - 端口重定向

php 文件不起作用

linux - 释放克隆的 skb(使用 skb_clone)将释放原始 skb?

c -/proc/interrupts 如何更新?

linux - kvm中hypercalls的入口在哪里?

linux - 如何解决 panic : no reachable servers

字符驱动节点未打开