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);