linux的驱动程序就是linux的一种内核模块,所以其基本的编写和编译步骤同内核模块的编写,参考:
http://blog.csdn.net/qitaosong/archive/2009/09/30/4621356.aspx
不同的是在驱动程序加载时需要通过register_chrdev()函数来注册设备,同时注册设备操作数据结构file_operations, 该数据结构定义了对设备的基本操作数据接口,对字符设备来说,基本函数接口有:open(), release(), read(), write(), ioctl(), llseek(), poll(). 具体定义见
在模块退出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 #include #include #include 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);