Linux驱动开发基本函数

1、驱动模块的加载和卸载

 /* 驱动入口函数 */
static int __init xxx_init(void)
{
                /* 入口函数具体内容 */
    int retvalue = 0;
    /* 注册字符设备驱动 */
    retvalue = register_chrdev(200, "chrtest", &test_fops);
     if(retvalue < 0){
        /* 字符设备注册失败,自行处理 */
     }
    return 0;
}


/* 驱动出口函数 */
static void __exit xxx_exit(void)
{
                /* 出口函数具体内容 */    

    /* 注销字符设备驱动 */
    unregister_chrdev(200, "chrtest");      
}
module_init(xxx_init);//注册模块加载函数
module_exit(xxx_exit);//注册模块卸载函数

2、字符设备注册与注销

函数原型

static inline int register_chrdev(unsigned int major,const char *name,
const struct file_operations *fops);
static inline void unregister_chrdev(unsigned int major,const char*name);
/*
major:主设备号
name:设备名字,指向一串字符串
fops:结构体 file_operations 类型指针
*/

函数一般运用驱动模块的入口函数和出口函数 如上。

3、实现设备的具体操作函数

file_operations 结构体就是设备的具体操作函数。

 static struct file_operations test_fops = {
 .owner = THIS_MODULE,
 .open = chrtest_open,
 .read = chrtest_read,
 .write = chrtest_write,
 .release = chrtest_release,
 };

加入设备操作函数:

/* 打开设备 */
static int chrtest_open(struct inode *inode, struct file *filp)
 {
    /* 用户实现具体功能 */
    return 0;
}

/* 从设备读取 */
static ssize_t chrtest_read(struct file *filp, char __user *buf,size_t cnt, loff_t *offt)
{
    /* 用户实现具体功能 */
    return 0;
}

 /* 向设备写数据 */
static ssize_t chrtest_write(struct file *filp,const char __user *buf,size_t cnt, loff_t *offt)
 {
    /* 用户实现具体功能 */
    return 0;
 }

 /* 关闭/释放设备 */
 static int chrtest_release(struct inode *inode, struct file *filp)
 {

    /* 用户实现具体功能 */
    return 0;
}

4、添加 LICENSE 和作者信息

MODULE_LICENSE("GPL");//使用GPL协议
MODULE_AUTHOR("wangcan");
MODULE_INFO(inttree, "Y");

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值