linux字元裝置驅動基礎框架

2021-10-03 21:58:14 字數 1800 閱讀 5303

#include #include #include #include #include #include #include #define count        1

#define name "chr_key0"

#define atomic_value 0 //定義巨集是否使用原子變數來限定在乙個時刻只能有乙個應用程式訪問驅動

struct key_dsc;

struct key_dsc *key_dev ;//表示乙個全域性裝置物件(後面動態分配記憶體)

static int key_dev_open(struct inode *inode, struct file *filp)

#endif

return 0;

}static ssize_t key_dev_read(struct file *filp, char __user *buf, size_t count, loff_t *offt)

static ssize_t key_dev_write(struct file *filp, const char __user *buf, size_t count, loff_t *offt)

static int key_dev_close(struct inode *inode, struct file *filp)

static struct file_operations key_fops = ;

static int __init key_dev_init(void)

//2.申請裝置號

ret = alloc_chrdev_region(&key_dev->key_dev_id, 0 ,count, name);

if(ret < 0)

//3.初始化cdev

cdev_init(&key_dev->key_cdev, &key_fops);

//4.新增cdev

ret = cdev_add(&key_dev->key_cdev,key_dev->key_dev_id, count);

if(ret < 0)

//5.建立類class

key_dev->key_class = class_create(this_module, name);

if(is_err(key_dev->key_class))

//6.建立裝置節點

key_dev->key_device = device_create(key_dev->key_class,null,key_dev->key_dev_id,null,name);

if(is_err(key_dev->key_device))

//7.硬體初始化

return 0;

error5:

class_destroy(key_dev->key_class);

error4:

cdev_del(&key_dev->key_cdev);

error3:

unregister_chrdev_region(key_dev->key_dev_id, count);

error2:

kfree(key_dev);

error1:

return ret;

}static void __exit key_dev_exit(void)

module_init(key_dev_init);

module_exit(key_dev_exit);

module_license("gpl");

linux 字元裝置驅動框架

linux 字元裝置驅動是3種型別中最簡單的一種,其實就是實現 file operations 中的函式,基本實現框架如下 1,需要包含的標頭檔案 include include include include include 2.定義及實現 file operations 中的函式,file op...

Linux字元裝置驅動框架總結

對於linux而言,一切皆檔案,在linux系統下,所有檔案都可以像文字檔案一樣open read write,那麼對於linux裝置驅動而言,比如現在有乙個點燈的驅動程式,它的裝置節點是 dev 當應用程式執行open read write的時候,是如何呼叫到驅動程式裡的open read wri...

linux 字元裝置 驅動框架 二

前面編寫了乙個簡單的 linux字元裝置驅動 linux driver 1 接下來簡單地來看一下字元裝置驅動的框架。在linux 字元裝置裡,有三個比較重要的資料結構,分別是 struct file operations,struct file和struct inode 下面來簡單的說明一下 這個結...