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

seq_file應用

seq_file接口,在kernel 2.6中將代替老的proc接口

seq_file接口的實現,引入了對象、迭代子等概念,這類似於C++中的泛型技術

如果對泛型技術有一定的了解,則會對seq_file接口的理解有一定的幫助

下面是原文的實例代碼,略作注釋:

/*
* Simple demonstration of the seq_file interface.
*
* $Id: seq.c,v 1.1 2003/02/10 21:02:02 corbet Exp $
*/
#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接口,需要實現4個函數:start()、next()、stop()、show(),這4個函數用於對設備的輸出信息的迭代訪問(控制)*/
/*
* The sequence iterator functions. We simply use the count of the
* next line as our internal position.
*/
/*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);
}
/*
* The show function.
*/
/*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;
}
/*
* Tie them all together into a set of seq_operations.
*/
/*seq_file接口的函數操作集*/
static struct seq_operations ct_seq_ops = {
.start = ct_seq_start,
.next = ct_seq_next,
.stop = ct_seq_stop,
.show = ct_seq_show
};
/*
* Time to set up the file operations for our /proc file. In this case,
* all we need is an open function which sets up the sequence ops.
*/
/*proc接口的open方法實現,open()函數將proc文件與seq_file接口的函數操作集關聯起來*/
static int ct_open(struct inode *inode, struct file *file)
{
return seq_open(file, &ct_seq_ops);
};
/*
* The file operations structure contains our open function along with
* set of the canned seq_ ops.
*/
/*proc接口的函數操作集,除open方法外,其他方法不需要實現,已經由seq_file的內部代碼實現完畢*/
static struct file_operations ct_file_ops = {
.owner = THIS_MODULE,
.open = ct_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release
};
/*
* Module setup and teardown.
*/
/*模塊初始化,創建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);

Copyright © Linux教程網 All Rights Reserved