linux 字符驱动驱动

由于没有经过完整测试代码中可能会有不足之出,如有网友发现还请斧正
这是一个学文档,所有代码仅供学习使用,请勿在生产环境中使用

字符驱动简介

字符驱动是linux驱动学习的第一站,该代码完成了一个最简单的字符驱动以及一个最小化打测试代码

代码示例

应用测试代码

代码仅做了open的测试

int main (int argc, char *argv[])
{
    int fd = -1;

    fd = open("/dev/chartest1",O_RDWR);
    if(-1 == fd ){
        printf("open file error\n");
        return -1;
    }
    printf("open file success\n");
    if(fd != -1){
        printf("close file\n");
        close(fd);
        fd = -1;
    }
    return EXIT_SUCCESS;
}
驱动代码

下面打代码只做示例,具体代码请参考代码文件char_driver.c

static dev_t major = -1;
static int const devcnt = 1;
struct cdev cdev;
struct device *char_dev = NULL;
static struct class *chartest_class;

/*定义一个 file_operations 结构体*/
static const struct file_operations chardev_dev_fops = {
    .owner      = THIS_MODULE,
    .llseek     = no_llseek,
    .read       = chardev_dev_read,
    .write      = chardev_dev_write,
    .unlocked_ioctl = chardev_dev_ioctl,
    .open       = chardev_dev_open,
    .release    = chardev_dev_release,
};

static int hello_init(void)
{
    unsigned int err;

    cdev_init(&cdev, &chardev_dev_fops); /*初始化字符驱动*/
    err = alloc_chrdev_region(&major, 0, devcnt , "unused"); /*动态申请设备号*/
    err = cdev_add(&cdev, major, 1);/*将设备注册到系统中*/
    chartest_class = class_create(THIS_MODULE, "testclass"); /*创建设备文件:先创建一个class然后在class下创建一个设备文件*/
    char_dev = device_create(chartest_class, NULL, major, NULL, "%s%d", "chartest", 1);

    return 0;
}

static void hello_exit(void)
{
    device_destroy(chartest_class, major);
    class_destroy(chartest_class);
    unregister_chrdev(major, "test");
    major = -1;
    cdev_del(&cdev);

    printk(KERN_INFO "%s\n",__func__);
}

module_init(hello_init);
module_exit(hello_exit);

[邮箱] :(liulf_pc@126.com)
[CSDN] :https://blog.csdn.net/qqstring
[仓库地址] :https://gitee.com/stringliulf/char_driver.git

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值