资源描述:
《实现一个简单的linux字符设备驱动》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实现一个简单的linux字符设备驱动步骤1: 编写驱动程序viewplaincopytoclipboardprint?1.#include 2.#include 3.#include 4.#include 5.#include 6.#include 7.#include 8.#include 9.#define
2、DEVICE_NAME "cdev_zhangwei" 10.int number_of_devices = 1; 11.struct cdev mydev; 12.dev_t dev = 0; 13.char data[128] = "/0"; // the data of my device 14.struct class *myclass; 15.static int mydev_open(struct inode *inode, struct file *file) 16.{ 17. pr_info("mydev driver open!/n"
3、); 18. return 0; 19.} 20.static int mydev_release(struct inode *inode, struct file *file) 21.{ 22. pr_info("mydev driver released!/n"); 23. return 0; 24.} 25.ssize_t mydev_write(struct file *file, const char __user *buf, size_t count, loff_t *f_pos) 26.{ 27. ssize_t ret
4、 = 0; 28. pr_info("mydev_write!/n"); 29. pr_info("writing %d bytes/n", count); 1. if (count > 127) 2. return -ENOMEM; 3. if (count < 0) 4. return -EINVAL; 5. if (copy_from_user(data, buf, count)) { 6. ret = -EFAULT; 7. } 8. else { 9.
5、 data[127] = ''/0''; 10. pr_info("kernel received: %s/n", data); 11. ret = count; 12. } 13. return ret; 14.} 15.static ssize_t mydev_read(struct file* filp, char* buf, size_t len,loff_t* off) 16.{ 17. if( copy_to_user(buf,data,len) ) 18. { 19. re
6、turn -EFAULT; 20. } 21. 22. return len; 23.} 24.struct file_operations mydev_fops = { 25. .owner = THIS_MODULE, 26. .open = mydev_open, 27. .read = mydev_read, 28. .write = mydev_write, 29. .release = mydev_release 30. 31.}; 32.static int __init myd
7、ev_init(void) 33.{ 34. int result, error; 35. result = register_chrdev(0, DEVICE_NAME, &mydev_fops); 1. pr_info("udev_cdev: get major number: %d/n", result); 2. dev = MKDEV(result, 0); 3. myclass = class_create(THIS_MODULE,