Created
July 23, 2019 15:09
-
-
Save qookei/37b2d4993b717c3fd2c1a17384479541 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <linux/module.h> | |
#include <linux/moduleparam.h> | |
#include <linux/init.h> | |
#include <linux/kernel.h> | |
#include <linux/fs.h> | |
MODULE_LICENSE("GPL"); | |
MODULE_AUTHOR("qookie"); | |
static int device_open(struct inode *, struct file *); | |
static int device_release(struct inode *, struct file *); | |
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 struct file_operations fops = { | |
read: device_read, | |
write: device_write, | |
open: device_open, | |
release: device_release | |
}; | |
#define BUF_SIZ 8192 | |
static char yes_buf[BUF_SIZ]; | |
static int major; | |
#define DEV_NAME "yes" | |
static int yesmod_init(void) { | |
size_t i; | |
printk(KERN_INFO "yesmod: initializing\n"); | |
for (i = 0; i < BUF_SIZ; i += 2) { | |
yes_buf[i] = 'y'; | |
yes_buf[i + 1] = '\n'; | |
} | |
major = register_chrdev(0, DEV_NAME, &fops); | |
if (major < 0) { | |
printk(KERN_ALERT "yesmod: registering char device failed with %d\n", major); | |
return major; | |
} | |
printk(KERN_INFO "yesmod: to use the device, run:\n"); | |
printk(KERN_INFO "yesmod: 'mknod /dev/" DEV_NAME " c %d 0'\n", major); | |
return 0; | |
} | |
static void yesmod_cleanup(void) { | |
printk(KERN_INFO "yesmod: deinitializing\n"); | |
unregister_chrdev(major, DEV_NAME); | |
} | |
static int device_open(struct inode *inode, struct file *file) { | |
try_module_get(THIS_MODULE); | |
return 0; | |
} | |
static int device_release(struct inode *inode, struct file *file) { | |
module_put(THIS_MODULE); | |
return 0; | |
} | |
static ssize_t device_read(struct file *filp, char *buffer, | |
size_t length, loff_t * offset) { | |
int actual = length > BUF_SIZ ? BUF_SIZ : length; | |
if (actual & 1) actual--; | |
memcpy(buffer, yes_buf, actual); | |
return actual; | |
} | |
static ssize_t device_write(struct file *filp, const char *buff, size_t len, loff_t * off) { | |
return -EINVAL; | |
} | |
module_init(yesmod_init); | |
module_exit(yesmod_cleanup); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment