Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> Linux 核心

Linux 內核實踐:用 seq_file 實作序列檔案

seq_file 機制提供了標準例程,讓「順序檔案」的處理變得毫不費力。這類檔案的內容通常是遍歷某筆資料項而產生,用戶端也多半從頭读到尾。seq_file 讓你能用最小代價實作它。順序檔案理論上仍可定位,只是效率不佳——逐項順序存取才是首選模式;某方面佔了優勢,往往就在另一方面付出代價。

seq_operations 的四個回呼

struct seq_operations {
    void *(*start) (struct seq_file *m, loff_t *pos);
    void (*stop)  (struct seq_file *m, void *v);
    void *(*next) (struct seq_file *m, void *v, loff_t *pos);
    int  (*show)  (struct seq_file *m, void *v);
};
  • start():遍歷開始時呼叫,負責初始化,回傳起始偏移或 SEQ_START_TOKEN,出錯回傳 ERR_PTR。
  • stop():遍歷結束時呼叫,完成清理。
  • next():找出下一個項目,回傳該項目或 NULL 表示結束。
  • show():呼叫 seq_printf()、seq_puts() 等,把該節點的資訊輸出。

seq_file 與 open 的關聯

由於 C 語言中任何資料塊都能用「記憶體位址+大小」傳遞,上述四個回呼搭配內核提供的通用讀寫、定位、釋放函式,就能把任意資料序列化給使用者。這些通用操作需要狀態支持,也就是 seq_file:

struct seq_file {
    char *buf; size_t size; size_t from; size_t count;
    loff_t index; loff_t read_pos; u64 version;
    struct mutex lock;
    const struct seq_operations *op;
    void *private;
};

buf 指向配置給使用者端的緩衝區,size 是緩衝區總量,count 是尚待送出的位元組數,from 是複製的起點;index 標記核心下一次寫入新紀錄的位置。index 與 from 的演變不同,因為「核心寫入緩衝區」與「把緩衝區複製到使用者空間」是兩件不同的事。

file_operations 只需自寫 open,其餘交給核心:

static int my_open(struct inode *inode, struct file *filp)
{
    return seq_open(filp, &my_seq_ops);
}

static const struct file_operations my_file_ops = {
    .open    = my_open,
    .read    = seq_read,
    .llseek  = seq_lseek,
    .release = seq_release,
};

seq_open 會配置 seq_file 實例、掛到 file->private_data,並把 op 記錄起來。

一個可運行的完整範例

#include <linux/init.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>

#define MAX_SIZE 10

struct my_data { int data; };
static struct my_data *md;

static struct my_data *my_data_init(void)
{
    int i;
    md = kmalloc(MAX_SIZE * sizeof(struct my_data), GFP_KERNEL);
    for (i = 0; i < MAX_SIZE; i++)
        (md + i)->data = i;
    return md;
}

static void *my_seq_start(struct seq_file *f, loff_t *pos)
{
    return (*pos < MAX_SIZE) ? pos : NULL;
}

static void *my_seq_next(struct seq_file *p, void *v, loff_t *pos)
{
    (*pos)++;
    return (*pos >= MAX_SIZE) ? NULL : pos;
}

static int my_seq_show(struct seq_file *f, void *v)
{
    unsigned int i = *(loff_t *)v;
    seq_printf(f, "The %d data is:%d\n", i, (md + i)->data);
    return 0;
}

static void my_seq_stop(struct seq_file *f, void *v) { }

static const struct seq_operations my_seq_ops = {
    .start = my_seq_start, .next = my_seq_next,
    .stop  = my_seq_stop,  .show = my_seq_show,
};

static int __init my_seq_init(void)
{
    struct proc_dir_entry *p;
    my_data_init();
    p = create_proc_entry("my_seq", 0, NULL);
    if (p)
        p->proc_fops = &my_file_ops;
    return 0;
}

static void __exit my_seq_exit(void)
{
    remove_proc_entry("my_seq", NULL);
}

module_init(my_seq_init);
module_exit(my_seq_exit);

載入模組後,cat /proc/my_seq 便會依序印出十筆資料。整個模式的重點在於:你只實作 start/next/stop/show 四個回呼,讀取、定位與釋放都由核心代勞。

Copyright © Linux教程網 All Rights Reserved