From Eratic Earthworm, 10 Months ago, written in Plain Text.
  1. #include <linux/init.h>
  2. #include <linux/module.h>
  3. #include <linux/fs.h>
  4. #include <linux/uaccess.h>
  5. #include <init.h>
  6. #include <slab.h>
  7. #include <cdev.h>
  8.  
  9. #define MYDEV_NAME "mycdrv"
  10. #define KBUF_SIZE (size_t) (10*PAGE_SIZE)
  11.  
  12. static char *kbuf;
  13. static dev_t first;
  14. static unsigned int count = 1;
  15. static int my_major = 700, my_minor = 0;
  16. static struct cdev *my_cdev;
  17.  
  18. static int mycdrv_open (struct inode *inode, struct file *file)
  19. {
  20.   printk(KERN_INFO "OPENING device: %s\n\n", MYDEV_NAME);
  21.   return 0;
  22. }
  23.  
  24. static int mycdrv_release (struct inode *inode, struct file *file)
  25. {
  26.   printk(KERN_INFO "CLOSING device: %s\n\n", MYDEV_NAME);
  27.   return 0;
  28. }
  29.  
  30. static ssize_t;
  31. mycdrv_read (struct file *file, char __user * buf, size_t lbuf, loff_t * ppos)
  32. {
  33.   int nbytes = lbuf - copy_to_user(buf, kbuf + *ppos, lbuf);
  34.   *ppos += nbytes;
  35.   prink(KERN_INFO "\n READING function, nbytes=%d, pos %d\n", nbytes, (int)*ppos);
  36.   return nbytes;
  37. }
  38. static ssize_t;
  39. mycdrv_write(struct file *file, char __user * buf, size_t lbuf, loff_t * ppos)
  40. {
  41.   int nbytes = lbuf - copy_from_user(buf, kbuf + *ppos, lbuf);
  42.   *ppos += nbytes;
  43.   prink(KERN_INFO "\n WRITING function, nbytes=%d, pos %d\n", nbytes, (int)*ppos);
  44.   return nbytes;
  45. }
  46.  
  47. static const struct file_operations mycdrv_fops = {
  48.   .owner = THIS_MODULE,
  49.   .read = mycdrv_read,
  50.   .write = mycdrv_write,
  51.   .open = mycdrv_open,
  52.   .release = mycdrv_release,
  53. };
  54.  
  55. static int __init my_init (void)
  56. {
  57.   kbuf = kmalloc(KBUF_SIZE, GFP_KERNEL);
  58.   first = MKDEV(my_major, my_minor);
  59.   register_chrdev_region(first, count, MYDEV_NAME);
  60.   my_cdev = cdev_alloc();
  61.   cdev_init(my_cdev, &mycdrv_fops);
  62.   cdev_add(my_cdev, first, count);
  63.   printk(KERN_INFO "\nSucceeded in registering character device %s\n", MYDEV_NAME);
  64.   return 0;
  65. }
  66.  
  67. static void __exit my_exit (void)
  68. {
  69.   cdev_del(my_cdev);
  70.   unregister_chrdev_region(first, count);
  71.   printk(KERN_INFO "\ndevice unregistered\n");
  72.   kfree(kbuf);
  73. }
  74.  
  75.  
  76. module_init(my_init);
  77. module_exit(my_exit);
  78.  
captcha