Skip to content

Instantly share code, notes, and snippets.

@kangear
Last active December 27, 2015 02:09
Show Gist options
  • Save kangear/7250199 to your computer and use it in GitHub Desktop.
Save kangear/7250199 to your computer and use it in GitHub Desktop.
freg.c sample DON'T EDIT.
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
/* 主设备号 */
#define MAJOR_NUM 250
static ssize_t freg_read(struct file* filp, char __user *buf, size_t count, loff_t* f_pos);
static ssize_t freg_write(struct file* filp, const char __user *buf, size_t count, loff_t* f_pos);
/* "freg"设备的全局变量 */
static int freg_var = 0;
static ssize_t freg_read(struct file *filp, char *buf, size_t len, loff_t *off)
{
/* 将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 *buf, size_t len, loff_t *off)
{
/* 将用户空间的数据复制到内核空间的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结构体 */
struct file_operations freg_fops = {
.owner = THIS_MODULE,
.write = freg_write,
.read = freg_read,
};
static int __init freg_init(void)
{
int ret;
printk(KERN_ALERT"Initializing freg device.\n");
/* 注册设备驱动 */
ret = register_chrdev(MAJOR_NUM, "freg", &freg_fops);
if (ret) {
printk("freg register failure");
}
else{
printk("freg register success");
}
return ret;
}
static void __exit freg_exit(void)
{
printk(KERN_ALERT"Destroy freg device.\n");
unregister_chrdev(MAJOR_NUM, "freg");
}
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