2012-06-16 64 views
4

當它的某個sys文件發生更改時是否可以通知模塊?我的任務是創建一個控制模塊內緩衝區大小的文件,當文件中的值改變時,我想調整緩衝區的大小。 我的另一個想法(如果我不能通知模塊)是每次使用模塊時檢查以前的值,然後調整緩衝區的大小。sysfs中的內核模塊參數 - 更改的快速響應

回答

9

這不是Sysfs的目的嗎?

當您創建一個kobject並在Sysfs(它是一個目錄)中給它一個表示時,然後爲該對象創建屬性,該屬性將成爲該目錄中的文件。您提供storeshow回撥到kobject,這基本上是對等的。 writeread

store是你想要的。它看起來像這樣:

ssize_t (*store)(struct kobject *kobj, struct attribute *attr, 
    const char *buffer, size_t size); 

您會收到內buffersize字節只要虛擬文件是寫在用戶的土地。

看一看這個模塊,它做它(從here拍攝):

#include <linux/module.h> 
#include <linux/kernel.h> 
#include <linux/init.h> 
#include <linux/fs.h> 
#include <linux/slab.h> 

struct my_attr { 
    struct attribute attr; 
    int value; 
}; 

static struct my_attr my_first = { 
    .attr.name="first", 
    .attr.mode = 0644, 
    .value = 1, 
}; 

static struct my_attr my_second = { 
    .attr.name="second", 
    .attr.mode = 0644, 
    .value = 2, 
}; 

static struct attribute * myattr[] = { 
    &my_first.attr, 
    &my_second.attr, 
    NULL 
}; 

static ssize_t default_show(struct kobject *kobj, struct attribute *attr, 
     char *buf) 
{ 
    struct my_attr *a = container_of(attr, struct my_attr, attr); 
    return scnprintf(buf, PAGE_SIZE, "%d\n", a->value); 
} 

static ssize_t default_store(struct kobject *kobj, struct attribute *attr, 
     const char *buf, size_t len) 
{ 
    struct my_attr *a = container_of(attr, struct my_attr, attr); 
    sscanf(buf, "%d", &a->value); 
    return sizeof(int); 
} 

static struct sysfs_ops myops = { 
    .show = default_show, 
    .store = default_store, 
}; 

static struct kobj_type mytype = { 
    .sysfs_ops = &myops, 
    .default_attrs = myattr, 
}; 

struct kobject *mykobj; 
static int __init sysfsexample_module_init(void) 
{ 
    int err = -1; 
    mykobj = kzalloc(sizeof(*mykobj), GFP_KERNEL); 
    if (mykobj) { 
     kobject_init(mykobj, &mytype); 
     if (kobject_add(mykobj, NULL, "%s", "sysfs_sample")) { 
      err = -1; 
      printk("Sysfs creation failed\n"); 
      kobject_put(mykobj); 
      mykobj = NULL; 
     } 
     err = 0; 
    } 
    return err; 
} 

static void __exit sysfsexample_module_exit(void) 
{ 
    if (mykobj) { 
     kobject_put(mykobj); 
     kfree(mykobj); 
    } 
} 

module_init(sysfsexample_module_init); 
module_exit(sysfsexample_module_exit); 
MODULE_LICENSE("GPL"); 

此外:在讀條目你可能想輸出緩衝區的大小給用戶。這通常是這樣做的方式。還要確保信息(讀取和寫入)以可讀的格式與Unix哲學保持一致。

更新:請參閱this recent interesting article關於創建由頂級內核開發人員之一Greg Kroah-Hartman編寫的Sysfs文件。

+0

這很有幫助!它看起來像default_store()應該返回len,否則發生寫錯誤... – pmod

+0

@pmod:寫錯誤,或不完整的寫?你是對的,雖然在這裏返回'sizeof(int)'是錯誤的,因爲[doc](https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt)表示store函數應該返回使用的字節數,這在這裏顯然與'sizeof(int)'無關。如果使用完整的緩衝區,那麼按照您的建議,直接返回'len'。 – eepp