linux字符设备驱动步骤

 

 linux 字符设备驱动步骤

 

1.      创建设备结构体:

Struct XXX_dev

{

        Struct cdev cdev;

        Unsigned value;

        /* other values */

};

2.      编写设备初始化函数:

Int XXX_init(void);

a. 根据主设设备号创建设备:dev_t dev = MKDEV(XXX_major, 0);

b. 注册创建的设备:

手动注册result = register_chrdev_region(dev, 1, “DEVICE NAME”); or

自动注册result = alloc_chrdev_region(&dev, 0, 1, “DEVICE NAME”);

c. 为注册成功的设备分配内存:

XXX_devp = kmalloc(sizeof(struct XXX_dev), GFP_KERNEL);

d. 初始化注册成功的内存:

Memset(XXX_devp, 0, sizeof(struct XXX_dev));

  1. 设置设备的设备结构体:

XXX_setup_cdev(XXX_devp, 0);

                        i.              初始化设备结构体的操作函数:

Struct XXX_dev *dev = XXX_devp;

Cdev_init(&dev -> cdev, &XXX_fops);

Dev -> cdev.owner = “THIS_MODULE”;

Dev -> cdev.ops = &XXX_fops;

                      ii.              初始化后将设备结构体加入设备中

Cdev_add(&dev -> cdev, devno, 1);

  1. 设置设备操作函数结构体:

Struct file_operations XXX_fops =

{

       .owner = THIS_MODULE,

        .read = XXX_read,    /* 函数指针*/

        .write = XXX_write,

        .ioctl = XXX_ioctl,

        .open = XXX_open,

        .release = XXX_release,

};

  1. 编写设备操作函数结构体中的函数:

int XXX_open(struct inode *inode, struct file *filp)

int XXX_release(struct inode *inode, struct file *filp)

ssize_t XXX_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)

ssize_t XXX_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos)

int XXX_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg)

3.      编写设备注销函数:

XXX_cleanup();

a.       删除设备结构体:

Cdev_del(&XXX_devp -> cdev);

b.      释放设备内存:

Kfree(XXX_devp);

c.       注销设备

Unregister_chrdev_region(MKDEV(XXX_major, 0), 1);

4.      设备模块与系统接口函数:

Module_init(XXX_init);

Module_exit(XXX_cleanup);

 

 

你可能感兴趣的:(linux,职场,休闲,设备驱动)