使用/proc 文件,只读的例子

来源:互联网 发布:手机免费网络电视直播 编辑:程序博客网 时间:2024/05/24 06:36

只用/proc文件是常用的调试方式,因为如果用很多的printk的话,对性能,及log显示都不是很好。

下面是一个简单的创建只读的proc文件的kernel module的例子。

例子中只是简单的输出了一句话,对于实际的项目可以打印不同的东西。

 

但是这个例子的缺点在于,使用proc文件读取时,只能读取一个page的大小?

/*
 * =====================================================================================
 *
 *       Filename:  proc.c
 *
 *    Description:  This is a standalone module to show the usage of
 *                  /proc file.
 *
 *        Version:  1.0
 *        Created:  11/21/2010 01:12:35 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (),
 *        Company: 
 *
 * =====================================================================================
 */
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>

#include <linux/kernel.h>    /* printk() */
#include <linux/slab.h>        /* kmalloc() */
#include <linux/fs.h>        /* everything... */
#include <linux/errno.h>    /* error codes */
#include <linux/types.h>    /* size_t */
#include <linux/proc_fs.h>
#include <linux/fcntl.h>    /* O_ACCMODE */
#include <linux/seq_file.h>
#include <linux/cdev.h>

#include <asm/system.h>        /* cli(), *_flags */
#include <asm/uaccess.h>    /* copy_*_user */

#include "scull.h"        /* local definitions */

MODULE_AUTHOR("Alessandro Rubini, Jonathan Corbet");
MODULE_LICENSE("Dual BSD/GPL");
/*
 *  buf:    point to a page size buffer allocate by kernel
 *          the content is displayed to user
 *  start:
 *  offset: offset and count is the same meaning as for the
 *  count:  read method
 *  eof:    point to an integer that must be set by the driver to signal that
 *          it has no more data to return
 *  data:   driver-specific data pointer, for internal bookkeeping
 */
int read_procmem(char *buf, char **start, off_t offset,
                   int count, int *eof, void *data)
{
    int i, j, len = 0;
    int limit = count - 80; /* Don't print more than this */

    len = sprintf(buf, "proc_file test/n");
    *eof = 1;/* delete this line seems work two? */
    return len;
}
int scull_init_module(void)
{
    PDEBUG("proc test/n");
    /* create file /proc/proc_test */
    create_proc_read_entry("proc_test", 0 /* default mode */,
            NULL /* parent dir */, read_procmem,
            NULL /* client data */);
    return 0;
}
void scull_cleanup_module(void)
{
    /* remove /proc/proc_test */
    remove_proc_entry("proc_test", NULL /* parent dir */);
    return;
}
module_init(scull_init_module);
module_exit(scull_cleanup_module);

原创粉丝点击