#include #include #include #include #include #include #include #include #include static dev_t first; // Global variable for the first device number static struct cdev c_dev; // Global variable for the character device structure static struct class *cl; // Global variable for the device class static int my_open(struct inode *i, struct file *f) { printk(KERN_INFO "Driver: open()\n"); return 0; } static int my_close(struct inode *i, struct file *f) { printk(KERN_INFO "Driver: close()\n"); return 0; } //static char c; static char text[20];// = "test\n"; static char *text_ptr = text; static ssize_t my_read(struct file *f, char __user *buf, size_t len, loff_t *off) { int bytes_read; bytes_read = 0; //text_ptr = text; if (*text_ptr == 0) { printk(KERN_INFO "Driver: read()%u bytes\n",bytes_read); return 0; } while (len && *text_ptr) { put_user(*text_ptr, buf); ++text_ptr; ++buf; --len; bytes_read++; } printk(KERN_INFO "Driver: read()%u bytes\n",bytes_read); printk(KERN_INFO "Data:%s\n",text); return bytes_read; } static ssize_t my_write(struct file *f, const char __user *buf, size_t len, loff_t *off) { size_t i; for (i = 0; i < len && i < sizeof(text) - 1; ++i) { //prefix ++? get_user(text[i], buf); ++buf; } /* text[i] = 'R'; text[i+1] = 'e'; text[i+2] = 'c'; text[i+3] = 'v'; text[i+1] = '\n'; */ text[i+1] = 0; text_ptr = text; printk(KERN_INFO "Driver: write() %u bytes\n",i); printk(KERN_INFO "Data:%s\n",text); return i; } /* if (get_user(text[i], buf)!=0)//(copy_from_user(&c, buf + len – 1, 1) != 0) return -EFAULT; else return len; }*/ static struct file_operations pugs_fops = { .owner = THIS_MODULE, .open = my_open, .release = my_close, .read = my_read, .write = my_write }; static int __init mfcd_init(void) /* Constructor */ { printk(KERN_INFO "Gun: mfcd registered"); if (alloc_chrdev_region(&first, 0, 3, "Andy") < 0) { return -1; } if((cl = class_create(THIS_MODULE, "chardrv"))==0) { unregister_chrdev_region(first,1); return -1; } if (device_create(cl, NULL, first, "%s", "mynull") == NULL) { class_destroy(cl); unregister_chrdev_region(first, 1); return -1; } cdev_init(&c_dev, &pugs_fops); if (cdev_add(&c_dev, first, 1) == -1) { device_destroy(cl, first); class_destroy(cl); unregister_chrdev_region(first, 1); return -1; } printk(KERN_INFO ": <%d, %d>\n", MAJOR(first), MINOR(first)); return 0; } static void __exit mfcd_exit(void) /* Destructor */ { cdev_del(&c_dev); device_destroy(cl, first); class_destroy(cl); unregister_chrdev_region(first, 1); unregister_chrdev_region(first, 3); printk(KERN_INFO "Gun: mfcd unregistered"); } module_init(mfcd_init); module_exit(mfcd_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Gun "); MODULE_DESCRIPTION("My First Character Driver");