一个使用 seq_file 接口的 proc_fs 例子

来源:互联网 发布:页面升级紧急通知域名 编辑:程序博客网 时间:2024/04/28 07:11
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <asm/uaccess.h>

static struct proc_dir_entry *pfile;

static char *myfruits[5] = {"apple", "orange", "banana", "watermelon", "pear"};

static void *my_seq_start(struct seq_file *s, loff_t *pos)
{
        if (*pos >= 5)
                return NULL;
        return myfruits[*pos];
}

static void *my_seq_next(struct seq_file *s, void *v, loff_t *pos)
{
        if (++*pos >= 5)
                return NULL;
        return myfruits[*pos];
}

static void my_seq_stop(struct seq_file *s, void *v)
{
    // nothing to do;
}

static int my_seq_show(struct seq_file *s, void *v)
{
        seq_printf(s, "%s ", (char *)v);
        return 0;
}

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

static int my_seq_open(struct inode *inode, struct file *file)
{
        return seq_open(file, &proc_seq_ops);
}

static struct file_operations proc_fops = {
        .open = my_seq_open,
        .read = seq_read,
        .llseek = seq_lseek,
        .release = seq_release,
};

static int __init myproc_init(void)
{
        pfile = proc_create("fruits", 0666, NULL, &proc_fops);
        if (!pfile) {
                printk(KERN_ERR "Can't create /proc/fruits/n");
                remove_proc_entry("mydir", NULL);
                return -1;
        }

        return 0;
}

static void __exit myproc_exit(void)
{
        remove_proc_entry("fruits", NULL);
}

module_init(myproc_init);
module_exit(myproc_exit);