Last active
December 27, 2015 02:09
-
-
Save kangear/7250788 to your computer and use it in GitHub Desktop.
That's OK, don't edit.
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/kernel.h> | |
#include <linux/fs.h> | |
#include <linux/cdev.h> | |
#include <asm/uaccess.h> | |
static struct cdev freg_cdev; //An instance of a character device | |
static dev_t ndev; //The node of the device | |
/* "freg"设备的全局变量 */ | |
static int freg_var = 0; | |
static ssize_t freg_read(struct file *filp, char __user *buf, size_t sz, loff_t *off) | |
{ | |
printk("In the freg_read() function!\n"); | |
/* 将freg_var从内核空间复制到用户空间 */ | |
if (copy_to_user(buf, &freg_var, sizeof(int))) { | |
return - EFAULT; | |
} | |
printk("freg_read enter ,the data is %d\n",freg_var); | |
return sizeof(int); | |
} | |
static ssize_t freg_write(struct file* filp, const char __user *buf, size_t count, loff_t* f_pos) | |
{ | |
printk("In the freg_write() function!\n"); | |
/* 将用户空间的数据复制到内核空间的freg_var */ | |
if (copy_from_user(&freg_var, buf, sizeof(int))) { | |
return -EFAULT; | |
} | |
printk("freg_write enter ,the data is %d\n",freg_var); | |
return sizeof(int); | |
} | |
// file_operations is a very important data struct in character type device | |
struct file_operations freg_ops = { | |
.owner = THIS_MODULE, | |
.read = freg_read, | |
.write = freg_write, | |
}; | |
// initialization function of the module | |
static int __init freg_init(void) | |
{ | |
int err; | |
printk(KERN_ALERT"Initializing freg device.\n"); | |
cdev_init(&freg_cdev, &freg_ops); //initialize the device instance | |
err = alloc_chrdev_region(&ndev, 0, 1, "freg"); //allocate the device node number dynamically | |
if(err < 0) | |
return err; | |
printk("freg_init():major=%d, minor=%d\n", MAJOR(ndev), MINOR(ndev)); | |
err = cdev_add(&freg_cdev, ndev, 1);//register the char_dev into the system | |
if(err < 0) | |
return err; | |
printk(KERN_ALERT"Succedded to initialize freg device.\n"); | |
return 0; | |
} | |
static void __exit freg_exit(void) | |
{ | |
printk(KERN_ALERT"Destroy freg device.\n"); | |
cdev_del(&freg_cdev); //unregister the char_dev from the system | |
unregister_chrdev_region(ndev, 1); //free the device node number | |
} | |
MODULE_LICENSE("GPL"); | |
MODULE_DESCRIPTION("Fake Register Driver"); | |
module_init(freg_init); | |
module_exit(freg_exit); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment