From 0c53df020c7b9a4bade2010a3eb260c4318e48f8 Mon Sep 17 00:00:00 2001 From: Thadeu Lima de Souza Cascardo Date: Wed, 19 May 2010 10:36:34 -0400 Subject: [PATCH] Create char device. --- hellochar.c | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/hellochar.c b/hellochar.c index e50ac2a..c2eecef 100644 --- a/hellochar.c +++ b/hellochar.c @@ -18,22 +18,54 @@ #include #include +#include +#include MODULE_LICENSE("GPL"); + static dev_t devnum; +static struct cdev *dev; + +static int hello_open(struct inode *ino, struct file *fp) +{ + printk(KERN_DEBUG "Hello, World!\n"); + return 0; +} + +static const struct file_operations hello_fops = { + .owner = THIS_MODULE, + .open = hello_open, +}; static int __init ch_init(void) { - int r; + int r = 0; r = alloc_chrdev_region(&devnum, 0, 256, "hello"); if (r) - return r; + goto out; + dev = cdev_alloc(); + if (!dev) { + r = -ENOMEM; + goto cdev_out; + } + dev->ops = &hello_fops; + r = cdev_add(dev, devnum, 256); + if (r) + goto add_out; printk(KERN_DEBUG "Allocate major %d\n", MAJOR(devnum)); return 0; +add_out: + kfree(dev); +cdev_out: + unregister_chrdev_region(devnum, 256); +out: + return r; } static void __exit ch_exit(void) { + cdev_del(dev); + kfree(dev); unregister_chrdev_region(devnum, 256); } -- 2.20.1