kmalloc()返回一个指向初始化期间分配的内存位置的指针,如果有一个包含cdev的结构指向它,为什么需要在文件操作open调用中执行container_of再次获取包含cdev的struct的地址?
答案 0 :(得分:3)
我认为你指的是这样的事情:
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
成员{ {1}}结构(通过struct scull_pipe
)。要获取inode->i_cdev
的容器地址(换句话说,cdev
实例的地址),您需要使用struct scull_pipe
:
container_of