Linux内核proc文件系统使用示例

本文分享了一段用于测试的Linux内核编程代码,作者为Sun Mingbao。该代码创建了一个名为'test'的proc文件系统入口,并实现了一个读取功能,能够显示作者对内核编程的喜爱。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*

 * kernel programming test code
 *
 * Copyright (C) 2014 Sun Mingbao <sunmingbao@126.com>
 * Dual licensed under the MIT and/or GPL licenses.
 *
 */
 
#include <linux/init.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include <linux/string.h>

MODULE_AUTHOR("Sun Mingbao <sunmingbao@126.com>");
MODULE_DESCRIPTION("kernel programming test code");
MODULE_VERSION("1.0");
MODULE_LICENSE("Dual MIT/GPL");

#define  MODULE_NAME    "test"

#define    WRITE_CONSOLE(fmt, args...) \
    do \
    { \
        printk(KERN_ALERT fmt,##args); \
    } while (0)

#define    DBG_PRINT(fmt, args...) \
    do \
    { \
        WRITE_CONSOLE(MODULE_NAME"_DBG:%s(%d)-%s:\n"fmt"\n", __FILE__,__LINE__,__FUNCTION__,##args); \
    } while (0)


static struct proc_dir_entry *my_proc_dir;
    
static char proc_file_contents[] = "I love kernel programming very much\n";
static int  proc_file_len = sizeof(proc_file_contents)-1;

static int misc_info_read_proc(char *buffer, char **start, off_t offset, int length, int *eof, void *data)
{
    int ret;
    ret=snprintf(buffer, length, "%s", proc_file_contents+offset);

    if(ret+offset==proc_file_len)
        *eof = 1;

    return ret;
}

static int __init create_my_proc_entries(void)
{
    my_proc_dir = proc_mkdir(MODULE_NAME, NULL);
    
    create_proc_read_entry("misc_info"
        ,0
        , my_proc_dir
        , misc_info_read_proc
        , NULL);

    return 0;
}

static int __init test_init(void)
{
    int retval;

    DBG_PRINT("start");
    retval=create_my_proc_entries();
    if (retval < 0)
    {
        goto EXIT;
    }
    
    DBG_PRINT("start succeed");
    
EXIT:
    return retval;
}

static void __exit remove_my_proc_entries(void)
{
    remove_proc_entry("misc_info", my_proc_dir);
    remove_proc_entry(MODULE_NAME, NULL);
}

static void __exit test_exit(void)
{
    DBG_PRINT("quit");
    remove_my_proc_entries();
}

module_init(test_init);
module_exit(test_exit);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值