kmalloc()返回一个指向初始化期间分配的内存位置的指针,如果使包含cdev的结构指向它,为什么需要在文件操作open call中执行container操作以再次获取包含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/

10-12 05:51