#include #include #include #include #include #define DEVICE_NAME "test" #define MODULE_NAME "test" static dev_t Devno; static struct cdev test_cdev; static struct mutex test_mutex; static ssize_t test_read(struct file *filp, char *buff, size_t len, loff_t *whence) { return 1; } static ssize_t test_write(struct file *filp, const char *buff, size_t len, loff_t *whence) { return 1; } static int test_open(struct inode *ino, struct file *filp) { if (mutex_lock_interruptible(&test_mutex)) return -ERESTARTSYS; printk("%s: test device is open.\n", MODULE_NAME); return 0; } static int test_close(struct inode *ino, struct file *filp) { printk("%s: test device is closed.\n", MODULE_NAME); mutex_unlock(&test_mutex); return 0; } static struct file_operations Fops = { .owner = THIS_MODULE, .read = test_read, .write = test_write, .open = test_open, .release = test_close }; static int __init test_init(void) { int rc; rc = alloc_chrdev_region(&Devno, 0, 1, DEVICE_NAME); if (rc < 0) { printk("%s: Registration failed...\n",MODULE_NAME); return rc; } printk("%s: Registration %s at major number %d\n", MODULE_NAME, DEVICE_NAME, MAJOR(Devno)); cdev_init(&test_cdev, &Fops); test_cdev.owner = THIS_MODULE; rc = cdev_add(&test_cdev, Devno, 1); if (rc < 0) { printk("%s: Device object not added!\n", MODULE_NAME); unregister_chrdev_region(Devno, 1); return rc; } printk("%s: Device added.\n", MODULE_NAME); mutex_init(&test_mutex); return 0; } static void __exit test_exit(void) { cdev_del(&test_cdev); unregister_chrdev_region(Devno, 1); printk("%s: Module removed.\n", MODULE_NAME); } module_init(test_init); module_exit(test_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Frank"); MODULE_DESCRIPTION("Simple char driver.");