最簡單的字元裝置驅動程式

2021-06-05 20:43:43 字數 2349 閱讀 4093

首先,先理清一下簡單字元裝置驅動程式的思路:

(1)申請裝置號

動態申請:int alloc_chrdev_region(dev_t *dev,unsignedbaseminor,unsignedcount,const char *name)

靜態申請:int register_chrdev_region(dev_tfrom,unsignedcount,const char *name)

成功返回0,失敗返回負數,並置於errno

(2)分配cdev,可以使用struct cdev *cdev_alloc(void) ,或者靜態定義全域性cdev變數

(3)初始化cdev

若使用動態分配,則需要進行初始化:void cdev_init(struct cdev *cdev,const struct file_operations *fops)  ,mem_cdev.owner = this_module;

若動態記憶體定義初始化:struct cdev *mem_cdev = cdev_alloc();    mem_cdev->ops = &fops;   mem_cdev->owner = this_module

(4)新增cdev

int cdev_add(struct cdev *p,dev_tdev,unsignedcount)

若使用記憶體模擬字元裝置,則還需申請空間:

mem_devp = kmalloc( 2 * sizeof(struct mem_dev), gfp_kernel);

if(!mem_devp)

memset(mem_devp, 0, sizeof(struct mem_dev));

for(i = 0; i < 2; i++)

申請失敗情況下,記得登出裝置號,使用void unregister_chrdev_region(dev_t from, unsigned count)

(5)構造file_operations結構體(結構體字段的初始化)

static const struct file_operations mem_fops =

;(6)實現file_operations支援的函式

int mem_open(struct inode *inode, struct file *filp)

static ssize_t mem_read(struct file *filp, char __user *buf, size_t size, loff_t *ppos)

else

return ret;

}static ssize_t mem_write(struct file *filp, const char __user *buf, size_t size, loff_t *ppos)

else

return ret;

}

static loff_t mem_llseek(struct file *filp, loff_t offset, int whence)

if((newpos < 0) || (newpos > memdev_size))

return -einval;

filp->f_pos = newpos;

return newpos;

}int mem_release(struct inode *inode, struct file *filp)

測試**:

#include

int main()

fwrite(buf, sizeof(buf), 1, fp);

fseek(fp, 0, seek_set);

strcpy(buf,"buf is null!");

printf("buf: %s\n",buf);

fread(buf, sizeof(buf), 1, fp);

printf("buf: %s\n",buf);

return 0;

}

linux裝置驅動程式 字元裝置驅動程式

先留個 有一起學習驅動程式的加qq295699450 字元裝置驅動 這篇比較惱火。載入成功,但是讀不出來資料,有知道怎麼回事的,留個言,一起討論下 資料結構 struct scull mem struct scull dev dev 整個驅動程式 如下 include include include...

Linux裝置驅動程式 字元裝置驅動程式

1.檢視主裝置號,次裝置號 進入 dev目錄執行ls l,第四,五列分別為主次裝置號,10,180,1,5,這些是主裝置號,而60,63這些就是次裝置號 130 shell android dev ls l crw rw r system radio 10,60 1969 12 31 21 00 a...

裝置驅動 字元裝置驅動程式

linux下的應用程式在訪問字元裝置時,一般都是通過裝置檔案訪問的。裝置檔案一般都存放在 dev目錄下。字元裝置檔案的第乙個標誌是c,如下所示 總結 每乙個檔案代表乙個裝置,在時間前面有兩個用逗號隔開的數字,第乙個數字是主裝置號,第二個數字是次裝置號。一般認為乙個主裝置號對應乙個驅動程式,這裡列出的...