歡迎您光臨本站 註冊首頁

linux字元設備驅動步驟

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0

linux 字元設備驅動步驟

1. 創建設備結構體:

Struct XXX_dev

{

Struct cdev cdev;

Unsigned value;

/* other values */

};

2. 編寫設備初始化函數:

Int XXX_init(void);

a. 根據主設設備號創建設備:dev_t dev = MKDEV(XXX_major, 0);

b. 註冊創建的設備:

手動註冊result = register_chrdev_region(dev, 1, “DEVICE NAME”); or

自動註冊result = alloc_chrdev_region(&dev, 0, 1, “DEVICE NAME”);

c. 為註冊成功的設備分配內存:

XXX_devp = kmalloc(sizeof(struct XXX_dev), GFP_KERNEL);

d. 初始化註冊成功的內存:

Memset(XXX_devp, 0, sizeof(struct XXX_dev));

  1. 設置設備的設備結構體:

XXX_setup_cdev(XXX_devp, 0);

i. 初始化設備結構體的操作函數:

Struct XXX_dev *dev = XXX_devp;

Cdev_init(&dev -> cdev, &XXX_fops);

Dev -> cdev.owner = “THIS_MODULE”;

Dev -> cdev.ops = &XXX_fops;

ii. 初始化后將設備結構體加入設備中

Cdev_add(&dev -> cdev, devno, 1);

  1. 設置設備操作函數結構體:

Struct file_operations XXX_fops =

{

.owner = THIS_MODULE,

.read = XXX_read, /* 函數指針*/

.write = XXX_write,

.ioctl = XXX_ioctl,

.open = XXX_open,

.release = XXX_release,

};

  1. 編寫設備操作函數結構體中的函數:

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

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

ssize_t XXX_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)

ssize_t XXX_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos)

int XXX_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg)

3. 編寫設備註銷函數:

XXX_cleanup();

a. 刪除設備結構體:

Cdev_del(&XXX_devp -> cdev);

b. 釋放設備內存:

Kfree(XXX_devp);

c. 註銷設備

Unregister_chrdev_region(MKDEV(XXX_major, 0), 1);

4. 設備模塊與系統介面函數:

Module_init(XXX_init);

Module_exit(XXX_cleanup);


[火星人 ] linux字元設備驅動步驟已經有515次圍觀

http://coctec.com/docs/linux/show-post-47660.html