1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #include <asm/uaccess.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/fs.h>
int init_module(void); void cleanup_module(void); static ssize_t device_read(struct file *, char *, size_t, loff_t *); static ssize_t device_write(struct file *, const char *, size_t, loff_t *); static int device_open(struct inode *, struct file *); static int device_release(struct inode *, struct file *);
#define DEVICE_NAME "csprojectedu"
static int major_version; static int device_is_open = 0; static char msg[1024]; static char *pmsg;
static struct file_operations fops = { .read = device_read, .write = device_write, .open = device_open, .release = device_release };
int init_module() { major_version = register_chrdev(0, DEVICE_NAME, &fops); if (major_version < 0) { printk(KERN_ALERT "Register failed, error %d.\n", major_version); return major_version; } printk(KERN_INFO "'mknod /dev/%s c %d 0'.\n", DEVICE_NAME, major_version); return 0; }
void cleanup_module() { unregister_chrdev(major_version, DEVICE_NAME); }
static ssize_t device_read(struct file *filp, char *buffer, size_t length, loff_t *offset) { int bytes = 0; if (*pmsg == 0) { return 0; } while (length && *pmsg) { put_user(*(pmsg++), buffer++); length--; bytes++; } return bytes; }
static ssize_t device_write(struct file *filp, const char *buff, size_t length, loff_t *offset) { return -EINVAL; }
static int device_open(struct inode *inode, struct file *file) { static int counter = 0; if (device_is_open) { return -EBUSY; } device_is_open = 1; sprintf(msg, "Device open for %d times.\n", ++counter); pmsg = msg; try_module_get(THIS_MODULE); return 0; }
static int device_release(struct inode *inode, struct file *file) { device_is_open = 0; module_put(THIS_MODULE); return 0; }
|