Linux字符设备驱动

本文介绍了如何在Linux内核中创建一个简单的HelloWorld模块,包含文件操作函数如read和write,以及杂项设备驱动的注册与释放。同时,还展示了如何在用户空间使用该设备进行读写操作。
摘要由CSDN通过智能技术生成

Hello World.c

#include <linux/module.h>        //模块的相关头文件
#include <linux/init.h>            //初始化的相关头文件
#include <linux/miscdevice.h>    //杂项设备驱动和相关头文件
#include <linux/fs.h>            //文件操作集合
#include <linux/uaccess.h>

ssize_t hd_fops_read (struct file *file, char __user *ubuf, size_t size, loff_t *loff_t){
    char kbuf[64] = "Hello Word";
    printk("Hello hd_fops_read\n");
     
    if( copy_to_user(ubuf,kbuf,strlen(kbuf)) != 0 ){
        printk("hd_fops_release error\n");
        return 0;
    }
    return 0;
}

ssize_t hd_fops_write (struct file *file, const char __user *ubuf, size_t size, loff_t *loff_t){
    char kbuf[64] = {0};
    printk("Hello hd_fops_write\n");
    
    if( copy_from_user(kbuf,ubuf,size) != 0 ){
        printk("hd_fops_write error\n");
        return 0;
    }
    printk("hd_fops_write urse is %s\n",kbuf);
    return 0;
}

int hd_fops_open (struct inode *inode, struct file *file){
    printk("Hello hd_fops_open\n");
    
    return 0;
}

int hd_fops_release (struct inode *inode, struct file *file){
    printk("Hello hd_fops_release\n");
    
    return 0;
}

struct file_operations hd_fops={//文件操作集合
    .owner   = THIS_MODULE,
    .read    = hd_fops_read,
    .write   = hd_fops_write,
    .open    = hd_fops_open,
    .release = hd_fops_release,
};

struct miscdevice hd_misc={         //杂项设备结构体
    .minor = MISC_DYNAMIC_MINOR,    //此设备号
    .name  = "zcy",                 //在dev下生成的设备节点
    .fops  = &hd_fops,
};

static int helloword_init(void){
    int ret = 0;
    ret = misc_register(&hd_misc);//注册杂项设备
    if( ret < 0 ){
        printk("misc_register error!!!\n");
        return 0;
    }
    printk("Hello Word!!!\n");
    return 0;
}

static void helloword_exit(void){
    misc_deregister(&hd_misc);//注销杂项设备驱动
    printk("Bye!!!\n");
}

module_init(helloword_init);
module_exit(helloword_exit);
MODULE_LICENSE("GPL");

APP.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc,char *argv[])
{
    int fd;
    char buf[64] = {0};
    char writebuf[64]="123456";
    fd = open("/dev/zcy",O_RDWR);
    if(fd < 0)
    {
        perror("open error\n");
        return fd;
    }
    read(fd,buf,sizeof(buf));
    printf("read buf is %s\n",buf);

    write(fd,writebuf,sizeof(writebuf));
    close(fd);
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值