快速业务通道

一个最简单的测试在/dev下生成字符设备的程序

作者 佚名技术 来源 Linux系统 浏览 发布时间 2012-03-24

先贴代码:

  1. #include <linux/init.h> /* Needed for the macros */
  2. #include <linux/kernel.h>
  3. #include <linux/module.h> /* Needed for all modules */
  4. #include <linux/fs.h>
  5. #include <linux/cdev.h>
  6. #include <linux/device.h>
  7. MODULE_LICENSE("Dual BSD/GPL");
  8. MODULE_AUTHOR("ttxgz");
  9. int hello_major = 555;
  10. int hello_minor = 0;
  11. int number_of_devices = 1;
  12. int memalloc_major = 111;
  13. int memalloc_minor = 1;
  14. struct cdev cdev;
  15. dev_t dev = 0;
  16. struct file_operations hello_fops = {
  17. .owner = THIS_MODULE
  18. };
  19. struct class *my_class;
  20. struct class *mem_class;
  21. static int __init hello_init(void)
  22. {
  23. int result;
  24. dev = MKDEV (hello_major, hello_minor);
  25. /* create your own class under /sysfs */
  26. my_class = class_create(THIS_MODULE, "my_class");
  27. if(IS_ERR(my_class))
  28. {
  29. printk("Err: failed in creating class.\n");
  30. return -1;
  31. }
  32. device_create( my_class, NULL, MKDEV(hello_major, hello_minor), NULL, "hello%d",0);
  33. mem_class = class_create(THIS_MODULE, "mem_class");
  34. device_create( mem_class, NULL, MKDEV(memalloc_major, memalloc_minor), NULL, "memalloc");
  35. printk(KERN_ALERT "Hello, world!/n");
  36. return 0;
  37. }
  38. static void __exit hello_exit(void)
  39. {
  40. dev_t devno = MKDEV (hello_major, hello_minor);
  41. device_destroy(my_class, MKDEV(hello_major, 0)); //delete device node under /dev
  42. class_destroy(my_class); //delete class created by us
  43. unregister_chrdev_region (devno, number_of_devices);
  44. devno = MKDEV(memalloc_major,memalloc_minor);
  45. device_destroy(mem_class, MKDEV(memalloc_major, memalloc_minor)); //delete device node under /dev
  46. class_destroy(mem_class); //delete class created by us
  47. printk (KERN_INFO "char driver cleaned up\n");
  48. printk(KERN_ALERT "Goodbye, cruel world/n");
  49. }
  50. module_init(hello_init);
  51. module_exit(hello_exit);

makefile是这样的:

  1. ifeq ($(KERNELRELEASE),)
  2. # Assume the source tree is where the running kernel was built
  3. # You should set KERNELDIR in the environment if it''s elsewhere
  4. KERNELDIR ?= /lib/modules/$(shell uname -r)/build
  5. # The current directory is passed to sub-makes as argument
  6. PWD := $(shell pwd)
  7. modules:
  8. $(MAKE) -C $(KERNELDIR) M=$(PWD) modules

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号