实现一个简单的LINUX字符设备驱动

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实现一个简单的linux字符设备驱动

步骤1:编写驱动程序

view plaincopy to clipboardprint?

1.#include

2.#include

3.#include

4.#include

5.#include

6.#include

7.#include

8.#include

9.#define 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");

18.return0;

19.}

20.static int mydev_release(struct inode*inode,struct file*file)

21.{

22.pr_info("mydev driver released!/n");

23.return0;

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=0;

28.pr_info("mydev_write!/n");

29.pr_info("writing%d bytes/n",count);

30.if(count>127)

31.return-ENOMEM;

32.if(count<0)

33.return-EINVAL;

34.if(copy_from_user(data,buf,count)){

35.ret=-EFAULT;

36.}

37.else{

38.data[127]=''/0'';

39.pr_info("kernel received:%s/n",data);

40.ret=count;

41.}

42.return ret;

43.}

44.static ssize_t mydev_read(struct file*filp,char*buf,size_t len,loff_t*off)

45.{

46.if(copy_to_user(buf,data,len))

47.{

48.return-EFAULT;

49.}

50.

51.return len;

52.}

53.struct file_operations mydev_fops={

54..owner=THIS_MODULE,

55..open=mydev_open,

56..read=mydev_read,

57..write=mydev_write,

58..release=mydev_release

59.

60.};

61.static int__init mydev_init(void)

62.{

63.int result,error;

64.result=register_chrdev(0,DEVICE_NAME,&mydev_fops);

65.pr_info("udev_cdev:get major number:%d/n",result);

66.dev=MKDEV(result,0);

67.myclass=class_create(THIS_MODULE,"mydev_class");

68.device_create(myclass,NULL,dev,NULL,DEVICE_NAME);

69.return0;

70.}

71.static void__exit mydev_exit(void)

72.{

73.cdev_del(&mydev);

74.unregister_chrdev_region(dev,number_of_devices);

75.device_destroy(myclass,dev);

76.class_destroy(myclass);

77.pr_info("Goodbye cdev!/n");

78.}

79.module_init(mydev_init);

80.module_exit(mydev_exit);

81.MODULE_LICENSE("GPL");

82.MODULE_DESCRIPTION("Simple cdev udev driver test");

相关文档
最新文档