简单的linux字符型驱动示例

linux的驱动程序就是linux的一种内核模块,所以其基本的编写和编译步骤同内核模块的编写,参考:

http://blog.csdn.net/qitaosong/archive/2009/09/30/4621356.aspx

 

不同的是在驱动程序加载时需要通过register_chrdev()函数来注册设备,同时注册设备操作数据结构file_operations, 该数据结构定义了对设备的基本操作数据接口,对字符设备来说,基本函数接口有:open(), release(), read(), write(), ioctl(), llseek(), poll(). 具体定义见<linux/fs.h>

 

在模块退出module_exit()时,调用unregister_chardev()卸载设备。

 

加载设备:insmod xx.ko, 参看设备 cat /proc/devices

创建设备节点: mknod /dev/xx  c 主设备号 次设备号

然后可以参看:ls /dev/xx  xx为设备名

 

参看内核消息,即printk()打印的消息,# dmesg

 

范例代码:

/****************************************************************/
/*file: chardev.c */
/*version:1.0 */
/*Anthor:  xxx */
/*time: 2009-xx-xx   */
/*Description: driver test */
/****************************************************************/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
MODULE_LICENSE("GPL");

#define MAJOR_NUM 250 /* major device number */

static ssize_t chardev_read(struct file *, char *, size_t, loff_t*);
static ssize_t chardev_write(struct file *, const char *, size_t, loff_t*);

/* init chardev's struct file_operations */
static struct file_operations chardev_fops =
{
    read: chardev_read,
    write: chardev_write,
};

static int chardev_var = 0; /* chardev's global variable */

int __init chardev_init(void)
{
    int ret;
   
    /* register device driver */
    ret = register_chrdev(MAJOR_NUM, "chardev", &chardev_fops);
    if(ret)
    {
        printk("chardev register failure");
    }  
    else
    {
        printk("chardev register success");
    }

    return ret;
}

static void __exit chardev_exit(void)
{
   
    /* unregister device driver */
    unregister_chrdev(MAJOR_NUM,"chardev");
    printk("chardev unregister");
}

static ssize_t chardev_read(struct file *filp, char *buf, size_t len, loff_t *off)
{
    /* copy chardev_var from kernel space to user space */
    if(copy_to_user(buf, &chardev_var, sizeof(int)))
    {
        return - EFAULT;
    }
   
    return sizeof(int);
}

static ssize_t chardev_write(struct file *filp, const char *buf, size_t len, loff_t *off)
{
    /* copy data from user space to kernel space chardev_var */
    if(copy_from_user(&chardev_var, buf, sizeof(int)))
    {
        return - EFAULT;
    }
   
    return sizeof(int);
}

module_init(chardev_init);
module_exit(chardev_exit);

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值