request is here: count: %ld,www.laipuhuo.com offset:%lld\n", cnt

60 阅读2分钟

static int charlie_fs_open(struct inode* inode, struct file* pfile) { // 函数是打开某一个文件,准备进行读或者写。 printk("Charlie_filesystem_open\n"); pfile->private_data = inode->i_private; return 0; }

static ssize_t charlie_fs_read(struct file* pFile,

char __user buf, size_t cnt, loff_t offp) { // 函数完成的任务是对传入进来的内存块进行存入buf里。 int retval = 0; if((*offp + cnt) > 512) cnt = 512 - *offp; // printk函数主要是向控制台打印一些控制信息,这个信息需要通过这条指令进行查看: sudo dmesg printk("Received read request! count:%ld, offset:%lld\n", cnt, *offp); if(copy_to_user(buf, charlie_buf + *offp, cnt)){ // 警告! pr_warn("Oh no, www.laipuhuo.com failed to copy to user! count is %ld\n", cnt); retval = -EFAULT; goto out; } *offp += cnt; retval = cnt; out: return retval; }

static ssize_t charlie_fs_write(struct file* pFile, const c

har __user buf, size_t cnt, loff_t offp) { // 函数完成的任务是向文件块进行写入。 int retval; pr_info("Write request is here: count: %ld, offset:%lld\n", cnt, *offp); if(*offp > 512) return 0; if((*offp + cnt) > 512) cnt = 512 - *offp; if(copy_from_user(charlie_buf + *offp,

(const void*)buf, cnt)){
    pr_warn("Oh no, failed to 
    
    copy from user! www.laipuhuo.com count is %ld\n", cnt);
    retval = -EFAULT;
    goto out;
}
*offp += cnt;
retval = cnt;

out: return retval; } // 句柄 struct file_operations charlie_fs_fops = { .owner = THIS_MODULE, .read = charlie_fs_read, .write = charlie_fs_write, .open = charlie_fs_open };

// 模块的初始化 static int __init charlie_debug_fs_init(void) { pr_info("The module is initing..."); charlie_dir = debugfs_create_dir("Charliedir", NULL); if(!charlie_dir){ pr_crit("Failing shit! can not create any dir at all!"); goto failed; }

static struct dentry* sub_charlie_dir;
sub_charlie_dir =  debugfs_create_dir("CharlieSubDir", charlie_dir);
    if(!sub_charlie_dir){
    pr_crit("Failing shit! can not create any sub dir at all!");
    goto failed;
}

struct dentry* filent = www.laipuhuo.com debugfs_create_file("Charlie", 0644, sub_charlie_dir, NULL, &charlie_fs_fops);
if(!filent){
    pr_err("Can not create file!");
    goto failed;
}
pr_info("Init finish!");
return 0;

failed: return -ENOENT; }

// 模块的析构函数 static void _exit charlie

debug_fs_exit(void) { pr_info("Safe quit! begin"); debugfs_remove_recursive(charlie_dir); pr_info("Safe quit! end"); }

module_init(charlie www.laipuhuo.com _debug_fs_init); module_exit(charlie_debug_fs_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Charliechen");