[Linux driver] Initialization, loading/unloading of character devices

The registration of a character device is divided into two parts: registering the device number and registering the device itself. The following two functions will be used to initialize the character device and load the character device into the kernel.


Table of contents

1. Character device data type

Second, the character device initialization function

3. Character device loading/unloading function

1. Device loading function

2. Device uninstall function


1. Character device data type

The cdev structure is used in Linux to represent a character device. The cdev structure and its related api functions are in the include/linux/cdev.h file. The definition of the structure is as follows.

struct cdev {
    struct kobject kobj;
    struct module *owner;               
    const struct file_operations *ops;    /* 字符设备文件操作函数 */
    struct list_head list;
    dev_t dev;                    /* 设备号 */
    unsigned int count;
};

static struct cdev chrdev;

Second, the character device initialization function

After the character device object is created, it needs to be initialized, and the function used for initialization is cdev_init. The function declaration is as follows:

void cdev_init(struct cdev *cdev, const struct file_operations *fops);

cdev: character device pointer (object)

fops: the current set of character device file operations

static struct cdev dev;		/* 字符设备 */

/*
 * 设备操作函数结构体
 */
static struct file_operations devfops = {
	.owner = THIS_MODULE, 
};

// 初始化字符设备
chrdev_led.dev.owner = THIS_MODULE;
cdev_init(&dev, &devfops);					// 初始化字符设备

3. Character device loading/unloading function

1. Device loading function

After creating the character device, we need to load the character device into the kernel along with the device number. The character device loading function is declared as follows:

int cdev_add(struct cdev *p, dev_t dev, unsigned count);

p : the character device pointer to add

dev: the device number registered for the current character device

count: the number of registered character devices

Return value: 0 for success; otherwise for failure

static dev_t devid;
static struct cdev dev;		            /* 初始化以后的字符设备 */

ret = cdev_add(&dev, devid, 1);			// 将字符设备添加到内核
if (ret != 0)
{
    return -1;
}

2. Device uninstall function

When uninstalling the driver, be sure to delete the corresponding character device from the kernel. The function used is cdev_del, and the function prototype is as follows:

void cdev_del(struct cdev *p);

The parameter p is the character device pointer to be deleted.

Guess you like

Origin blog.csdn.net/challenglistic/article/details/131881618