Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

seq_file 介面應用:在 2.6 內核中寫出可迭代的 /proc 檔案

在 2.6 內核中,seq_file 介面將取代老式的 proc 介面。它的實作引入了「物件」與「迭代子」的概念,思路近似 C++ 的泛型技術——若你對泛型有概念,理解起來會快很多。

以下以官方範例為基礎,加上逐段註解。

/*
* Simple demonstration of the seq_file interface.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/fs.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
MODULE_AUTHOR("Jonathan Corbet");
MODULE_LICENSE("Dual BSD/GPL");

/* 使用 seq_file 介面,需實作 start()、next()、stop()、show() 四個函數,
用於對設備輸出資訊做迭代式存取(控制) */

/* start():設定存取的起始位置,本範例的「位置」等同於 proc 檔的位移量;
回傳值作為迭代子 */
static void *ct_seq_start(struct seq_file *s, loff_t *pos)
{
loff_t *spos = kmalloc(sizeof(loff_t), GFP_KERNEL);
if (! spos)
return NULL;
*spos = *pos;
return spos;
}

/* next():決定迭代子的移動步長,此處每次讓位移量加 1;回傳新的迭代子 */
static void *ct_seq_next(struct seq_file *s, void *v, loff_t *pos)
{
loff_t *spos = (loff_t *) v;
*pos = ++(*spos);
return spos;
}

/* stop():負責清理工作 */
static void ct_seq_stop(struct seq_file *s, void *v)
{
kfree (v);
}

/* show():向 proc 檔輸出需要呈現的內容,此處僅印出迭代子的序號 */
static int ct_seq_show(struct seq_file *s, void *v)
{
loff_t *spos = (loff_t *) v;
seq_printf(s, "%Ld\n", *spos);
return 0;
}

/* 把四個函數綁成 seq_operations 集合 */
static struct seq_operations ct_seq_ops = {
.start = ct_seq_start,
.next = ct_seq_next,
.stop = ct_seq_stop,
.show = ct_seq_show
};

/* proc 介面的 open 方法:把 proc 檔與 seq_file 的函數操作集關聯起來 */
static int ct_open(struct inode *inode, struct file *file)
{
return seq_open(file, &ct_seq_ops);
};

/* proc 介面的 file_operations:除 open 之外其餘方法都已由 seq_file 內部實作,
直接沿用現成的 seq_read、seq_lseek、seq_release 即可 */
static struct file_operations ct_file_ops = {
.owner = THIS_MODULE,
.open = ct_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release
};

/* 模組初始化:建立 proc 檔 */
static int ct_init(void)
{
struct proc_dir_entry *entry;
entry = create_proc_entry("sequence", 0, NULL);
if (entry)
entry->proc_fops = &ct_file_ops;
return 0;
}

/* 模組卸載:刪除所建立的 proc 檔 */
static void ct_exit(void)
{
remove_proc_entry("sequence", NULL);
}

module_init(ct_init);
module_exit(ct_exit);

整份程式最需要理解的是分工:你只實作 start、next、stop、show 這四個與「怎麼走、走到哪、怎麼印」有關的函數,而 read、llseek、release 這些與使用者空間如何反覆讀取的細節,全部交給 seq_file 框架處理。載入模組後 cat /proc/sequence,就會看到 0、1、2…… 一路遞增的輸出。

Copyright © Linux教程網 All Rights Reserved