Skip to content

Instantly share code, notes, and snippets.

@kangear
Last active December 27, 2015 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kangear/7262276 to your computer and use it in GitHub Desktop.
Save kangear/7262276 to your computer and use it in GitHub Desktop.
is simple DON'T edit.
#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 int freg_major = 250;
static int freg_minor = 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
ndev = MKDEV(freg_major, freg_minor);
err = register_chrdev_region(ndev, 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