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

Linux procfs开发指南(部分翻译并做了精简)
Linux Kernel Procfs Guide
Chapter 1. Introduction
    /proc文件系统(procfs)在linux内核中是一个特殊的文件系统,是一个虚拟的文件系统,只存在于内存中
    注:proc/sys是sysctl文件,不属于procfs
Chapter 2. Managing procfs entries
    要使用procfs,需包含#include <linux/proc_fs.h>
    1.Creating a regular file
        struct proc_dir_entry* create_proc_entry(const char* name,mode_t mode, struct proc_dir_entry* parent);
            parent为NULL时,表示文件建立在/proc目录下,失败返回NULL
            create_proc_read_entry:创建并初始化一个procfs入口in one single call
    2. Creating a symlink        
        struct proc_dir_entry* proc_symlink(const char* name, struct proc_dir_entry* parent, const char* dest);
        在parent目录下创建一个从name到dest的符号链接,像:ln -s dest name
    3. Creating a device    
        struct proc_dir_entry* proc_mknod(const char* name, mode_t mode,struct proc_dir_entry* parent, kdev_t rdev);
        创建一个名为name设备文件,mode参数必须包含S_IFBLK或者S_IFCHR,像:mknod --mode=mode name rdev
    4. Creating a directory    
        struct proc_dir_entry* proc_mkdir(const char* name, struct proc_dir_entry* parent);
        在parent目录下创建名为name的目录
    5.Removing an entry
        void remove_proc_entry(const char* name, struct proc_dir_entry* parent);      
        从procfs中移除parent目录下的name入口。注意它不会递归移除
Chapter 3. Communicating with userland             
    procfs对文件的读写并不是直接的,而是通过call back函数来操作read_proc and/or write_proc
    在create_proc_entry函数返回一个proc_dir_entry* entry,然后设置
        entry->read_proc = read_proc_foo;
        entry->write_proc = write_proc_foo;
    1. Reading data    
        kernel向用户返回数据    
        int read_func(char* page, char** start, off_t off, int count,int* eof, void* data);
        从start处的off偏移处开始写最多count个字节的内容到page中。
    2. Writing data    
        用户写数据到kernel
        int write_func(struct file* file, const char* buffer, unsigned long count, void* data);
        从buffer中读count字节,buffer不存在于kernel memory空间,所以需要使用copy_from_user函数,file常NULL
    3.A single call back for many files    
        struct proc_dir_entry* entry;
        struct my_file_data *file_data;
        file_data = kmalloc(sizeof(struct my_file_data), GFP_KERNEL);
        entry->data = file_data;
        int foo_read_func(char *page, char **start, off_t off,
        int count, int *eof, void *data)
        {
        int len;
        if(data == file_data) {
        /* special case for this file */
        } else {
        /* normal processing */