Linux 2.6.x内核的`procfs1.c`的现代版本是什么?

时间:2014-03-20 20:10:25

标签: linux-kernel kernel-module

当我遇到第5章中的第一个示例procfs1.c时,我一直关注Linux 2.6 Kernel Module Programming Guide

它不会开箱即用,在检查了各种相关问题之后,我还需要花一些时间来找出正确的更改,以使其按预期编译和工作。

因此,我将来会为人们发布更新的代码。我正在运行内核2.6.32-279.el6.x86_64

1 个答案:

答案 0 :(得分:0)

以下是适用于内核版本2.6.32-279.el6.x86_64的示例的更新版本。

/*
 *  procfs1.c -  create a "file" in /proc
 *
 */

#include <linux/module.h>   /* Specifically, a module */
#include <linux/kernel.h>   /* We're doing kernel work */
#include <linux/proc_fs.h>  /* Necessary because we use the proc fs */

#define procfs_name "helloworld"

/**
 * This structure hold information about the /proc file
 *
 */
struct proc_dir_entry *Our_Proc_File;


static ssize_t procfile_read(struct file *filp,   
               char *buffer,    
               size_t length,   
               loff_t * offset)
{
    int ret;

    printk(KERN_INFO "procfile_read (/proc/%s) called\n", procfs_name);

    if (*offset > 0) {
        /* we have finished to read, return 0 */
        ret  = 0;
    } else {
        /* fill the buffer, return the buffer size */
        ret = sprintf(buffer, "HelloWorld!\n");
        *offset = ret;
    }

    return ret;
}

static struct file_operations fops = {
    .owner = THIS_MODULE,
    .read = procfile_read,
};

int init_module()
{

    Our_Proc_File = proc_create(procfs_name, S_IFREG | S_IRUGO, NULL, &fops);
    if (Our_Proc_File == NULL) {
        remove_proc_entry(procfs_name, NULL);
        printk(KERN_ALERT "Error: Could not initialize /proc/%s\n",
               procfs_name);
        return -ENOMEM;
    }

    Our_Proc_File->uid   = 0;
    Our_Proc_File->gid   = 0;
    Our_Proc_File->size      = 37;

    printk(KERN_INFO "/proc/%s created\n", procfs_name);    
    return 0;   /* everything is ok */
}

void cleanup_module()
{
    remove_proc_entry(procfs_name, NULL);
    printk(KERN_INFO "/proc/%s removed\n", procfs_name);
}