日期:2014-05-16  浏览次数:20541 次

在proc文件系统中实现程序输入和输出,怎么实现?
想编程实现在/proc下创建一个文件,可以通过这个文件查看程序输出的一些信息
就像使用/proc/meminfo查看内存信息一样

查了很久没有找到相关资料,只找到说要写个内核模块,没有应用程序接口。

求指点

------解决方案--------------------
C/C++ code

//你自己写个makefile了。
#include <linux/version.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/mm.h>
#include <asm/uaccess.h>

static char icinfobuf[BUF_MAXLEN];//你可以在其他模块中向其中写入数据了,我这里通过icinfo_copy写的

static int icinfo_read_proc(char* page,char **start, off_t off,int count,int *eof,void *data)
{
    sprintf(page,"%s\n",(char*)icinfobuf);
    return sizeof(icinfobuf);
}

static int icinfo_write_proc(struct file* file,const char __user* buffer,unsigned long count,void *data)
{    
    /* no use at the moment */
    return sizeof(icinfobuf);
}

void icinfo_copy(char* icinfo)
{
    strcat(icinfobuf,icinfo);
}
EXPORT_SYMBOL_GPL(icinfo_copy);

static int __init procfs_icinfo_init(void)
{
    struct proc_dir_entry* entry;

    memset(icinfobuf,0,sizeof(icinfobuf));
    entry=create_proc_entry("icinfo",S_IRWXO|S_IRWXU|S_IRWXG,NULL);

    if(entry)
    {
        entry->read_proc=&icinfo_read_proc;
        entry->write_proc=&icinfo_write_proc;
    }
    else
        printk("<icinfo.c>: %s Create /proc/icinfo failed!\n",__func__);
    return 0;
}
static void __exit procfs_icinfo_exit(void)
{
    remove_proc_entry("icinfo",NULL);
}
module_init(procfs_icinfo_init);
module_exit(procfs_icinfo_exit);
MODULE_LICENSE("GPL");

------解决方案--------------------
调用内核函数: create_proc_entry()等等
参考: http://bbs.chinaunix.net/viewthread.php?tid=1972121