C语言创建自己的设备(实例编程)
来源:优易学  2011-2-17 10:34:50   【优易学:中国教育考试门户网】   资料下载   IT书店
  我们在内核里面有时候项纪录一些自己的东西,其中有个好方法就是创建一个自己的特有的设备。这样我们可以在需要记录东西的地方,就调用这个设备的接口函数,这样很方便。
  这里我们创建一个很基本的设备驱动,主要是看看一个设备驱动的框架,这个例子重的设备驱动没有任何实际的功能。:)
  #define module
  #define __kernel__
  #include <linux/module.h>
  #include <linux/kernel.h>
  #include <linux/string.h>
  #include <linux/fs.h>
  #include <linux/malloc.h>
  #include <asm/unistd.h>
  #include <sys/syscall.h>
  #include <asm/fcntl.h>
  #include <asm/errno.h>
  #include <linux/types.h>
  #include <linux/dirent.h>
  static int driver_open(struct inode *i, struct file *f)
  {
  printk(\"<1>open function\\n\");
  return 0;
  }
  static struct file_operations fops = {
  null, /* owner */
  null, /*lseek*/
  null, /*read*/
  null, /*write*/
  null, /*readdir*/
  null, /*poll*/
  null, /*ioctl*/
  null, /*mmap*/
  driver_open, /*open, take a look at my dummy open function*/
  null, /*release*/
  null, /*fsync...*/
  null,
  null,
  null,
  null,
  null
  };
  int init_module(void)
  {
  if(register_chrdev(30, \"mydriver\", &fops)) return -eio;
  return 0;
  }
  void cleanup_module(void)
  {
  /*unregister our driver*/
  unregister_chrdev(30, \"mydriver\");
  }
  在上面的代码中最重要的一个函数是:register_chrdev(...),这个函数在系统里面注册了我们的驱动程序,主设备号码是30。如果我们需要访问这个设备,则要这样做:
  # mknod /dev/driver c 30 0
  # insmod mydriver.o
  然后你就可以在自己的程序里面使用这个设备了。
  the file_operations 结构体提供了所有的函数,直接使用就可以了。注意,如果需要在设备里面log一些东西的话,就可以自己处理了。例如在write这个函数里面提供一些处理之类的。

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训