基于Linux 3.10.49内核添加字符驱动(2)

/// @brief
///
/// @param file
/// @param offset  :上层应用lseek(int fd, off_t offset, int whence)的offset
/// @param where    :上层应用lseek(int fd, off_t offset, int whence)的whence
///
/// @return        :上层应用lseek(int fd, off_t offset, int whence)的返回值
loff_t mydemodev_llseek(struct file *file, loff_t offset, int where) {
    // 没有 加锁
    loff_t pos = file->f_pos + offset;

switch(where) {
        case SEEK_SET:
            if (offset >= MYDEMO_BUF_LEN || offset < 0) {
                return -EINVAL;
            }
            file->f_pos = offset;
            break;
        case SEEK_CUR:
        case SEEK_END:
            if (pos >= MYDEMO_BUF_LEN || pos < 0) {
                return -EINVAL;
            }
            file->f_pos = pos;
            break;
        default:
            return -EINVAL;
            break;
    }
    printk(KERN_WARNING "[%s %s %d] pos = %lld iminor(file->f_inode) = %u\n", __FILE__, __func__, __LINE__, file->f_pos, iminor(file->f_inode));

g_llMyDemoPos = file->f_pos;
    return file->f_pos;
}

static const struct file_operations mydemodev_fops = {
 .owner  = THIS_MODULE,
    .llseek  = mydemodev_llseek,                  // 1-2  --|
    .read  = mydemodev_read,                    // 1-2  --|
    .write  = mydemodev_write,                    // 1-2  --|这一步写上, 高级操作.
 // .unlocked_ioctl = i2cdev_ioctl,
    .open  = mydemodev_open,                    // 1-1  --|
    .release = mydemodev_release,                  // 1-1  --| 这一步写上, 基本上就可以看到效果了.
};

static struct class *mydemo_dev_class;


static int __init mydemo_dev_init(void)
{
 int res;

printk(KERN_INFO "my char dev demo entries driver\n");

res = register_chrdev(MYDEMO_MAJOR, "mydemo", &mydemodev_fops);            //1. 注册字符设备
 if (res)
  goto out;

mydemo_dev_class = class_create(THIS_MODULE, "mydemo-class");              //2. 生成class, 在 /sys/class/ 下生成mydemo-class文件夹
 if (IS_ERR(mydemo_dev_class)) {
  res = PTR_ERR(mydemo_dev_class);
  goto out_unreg_chrdev;
 }
    device_create(mydemo_dev_class,NULL,MKDEV(MYDEMO_MAJOR, MYDEMO_MINNOR),NULL,"mydemo-dev" "%d", MYDEMO_MINNOR); //3. 生成class, 在 /dev/ 下生成mydemo-dev9节点.

return 0;

class_destroy(mydemo_dev_class);
out_unreg_chrdev:
 unregister_chrdev(MYDEMO_MAJOR, "mydemo");
out:
 printk(KERN_ERR "%s: Driver Initialisation failed\n", __FILE__);
 return res;
}

static void __exit mydemo_dev_exit(void)
{
 printk(KERN_INFO "my char dev demo out driver\n");
 class_destroy(mydemo_dev_class);
 unregister_chrdev(MYDEMO_MAJOR, "mydemo");
}

MODULE_AUTHOR("EastonWoo <31417071@qq.com>");
MODULE_DESCRIPTION("my char dev demo entries driver");
MODULE_LICENSE("GPL");

module_init(mydemo_dev_init);
module_exit(mydemo_dev_exit);

6. 修改drivers/Makefile:

添加obj-$(CONFIG_MY_DEMO)        += MyDemo/

7. 修改drivers/char/Kconfig:

添加source "drivers/MyDemo/Kconfig"

这样就完成了.可以编译测试了.

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/4083a2749568a151bc4765aa50643842.html