2014-10-09 136 views
1

我嘗試對debugfs文件實現寫入功能。我希望我可以使用echo "hello" > /sys/kernel/debugfs/mydir/myfile向該文件寫入一個字符串。並使用echo "world" >> /sys/kernel/debugfs/mydir/myfilehello後追加world。我在實現中發現了兩個問題。一個是echo命令會在輸入字符串的長度超過緩衝區大小時卡住。另一個是echo "world" >> /sys/kernel/debugfs/mydir/myfile從不附加字符串。相反,它新建一個字符串。以下是我的實施。對debugfs文件執行寫入功能

#include <linux/module.h>  /* Needed by all modules */ 
#include <linux/kernel.h>  /* Needed for KERN_INFO */ 
#include <linux/init.h>   /* Needed for the macros */ 
#include <linux/miscdevice.h> 
#include <linux/uaccess.h> 
#include <linux/debugfs.h> 
#include <linux/fs.h> 
#include <linux/sched.h> 
MODULE_LICENSE("GPL"); 

#define BUF_SIZE 10 

static char foo_buf[BUF_SIZE]; 
static struct dentry *debug_dir; 
static struct dentry *debug_foo; 

static ssize_t foo_read(struct file *file, char __user *buf, size_t count, 
      loff_t *f_pos) 
{ 
    return simple_read_from_buffer(buf, count, f_pos, foo_buf, sizeof(foo_buf)); 
} 

static ssize_t foo_write(struct file *file, const char __user *buf, size_t count, 
        loff_t *f_pos) 
{ 
    size_t ret; 

    if (*f_pos > BUF_SIZE) 
      return -EINVAL; 
    ret = simple_write_to_buffer(foo_buf, sizeof(foo_buf), f_pos, buf, count); 
    if (ret < 0) 
      return ret; 
    foo_buf[ret] = '\0'; 

    return ret; 
} 

static const struct file_operations foo_fops = { 
    .owner = THIS_MODULE, 
    .read = foo_read, 
    .write = foo_write, 
}; 

static int __init debugfs_start(void) 
{ 

    pr_err("init debugfs"); 

    debug_dir = debugfs_create_dir("mydir", NULL); 
    if (debug_dir == NULL) { 
      pr_err("debugfs create my dir failed"); 
      return -ENOMEM; 
    } 

    debug_foo = debugfs_create_file("foo", 0744, debug_dir, 
             NULL, &foo_fops); 
    if (!debug_foo) { 
      debugfs_remove(debug_dir); 
      return -ENOMEM; 
    } 
    return 0; 
} 

static void __exit debugfs_end(void) 
{ 
    pr_err("exit debugfs"); 
    debugfs_remove_recursive(debug_dir); 
} 

module_init(debugfs_start); 
module_exit(debugfs_end); 

回答

0

一種是將echo命令卡住如果輸入字符串的長度是 過緩衝區的大小。

這是因爲它會不斷嘗試寫入文件,而每次嘗試都會失敗。

另一個是echo「world」>> /sys/kernel/debugfs/mydir/myfile永遠不會追加字符串。相反,它 新的一個字符串。

這是預計與您的實施。如果要追加它,您需要將新的字符串添加到現有的字符串中。也就是說,你需要保留一個字符串長度的記錄。但是這是 不同於特定於進程的打開文件的f_pos。

如何識別用戶將使用哪些命令(echo>或echo >>)?

所以你的意思是用戶在打開它後是否「截斷」文件? debugfs似乎不支持seek,但我想你可以提供你的.open函數和.llseek函數來實現它。如果打開APPEND文件,則需要在文件末尾看到該文件。

對不起,我不能提供完整的代碼,但只是一些指針。

+0

f_pos特定於進程打開文件。比如說,你可以有多個進程打開一個文件,每個進程都有自己的f_pos。 – tristan 2014-10-09 08:34:17

+0

如何識別用戶將使用哪些命令(echo>或echo >>)? – house 2014-10-09 08:47:46

+0

我認爲 - 但我還沒有證實 - 區別在於'>'應該做倒帶(或者可能不是,如果它可以假設在文件的頭部),而'>>'應該做一個fseek結束。 – 2017-02-09 15:59:23