Linux kernel (without create_proc_entry func) Proc文件系统的实例

55 篇文章 1 订阅
13 篇文章 0 订阅

proc文件系统

/proc 目录就是Linux的proc文件系统了, 这里面存放内核的配置信息, 网络配置系统, 以及进程的状态都是以pid明明的目录。总之, 关于内核的基本配置你就可以找到。

内核更新

在内核的迭代过程中,总有一些接口被废弃, create_proc_entry就是其中之一。
依稀记得,去年的时候一直想写个proc文件系统测试下, 直到上个月才有时间来做这个事情。当初让我试了就不测试的原因就是那个create_proc_entry函数的弃用, 网上能搜索的例子基本都是用这个函数。

样例代码

#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <asm/uaccess.h>
#include <linux/slab.h>
static char *buffer = NULL;

static int hello_proc_show(struct seq_file *m, void *v) {
  seq_printf(m, "Hello proc!\n");
  seq_printf(m, "buffer=%s\n", buffer);
  int i = 0;

  if (buffer != NULL)
  {  
    if (buffer[0] == 's')
    {
      for (i = 0; i < 10; i++)
        seq_printf(m, "i = %d\n", i);
    }
  }
  return 0;
}

static ssize_t hello_proc_write(struct file *file, const char *buffer, size_t len,
  loff_t *off)
{
  int user_len = 0;
  user_len = len;
  buffer = (char *)kmalloc(user_len+1, GFP_KERNEL);
  memset(buffer, 0, user_len + 1);
  if (copy_from_user(buffer, buffer, user_len))
  {
    printk( "hello_proc error\n");
    return -EFAULT;
  }
  printk( "userlen=%d\n", user_len);
  return user_len;
}

static int hello_proc_open(struct inode *inode, struct  file *file) {
  return single_open(file, hello_proc_show, NULL);
}

static const struct file_operations hello_proc_fops = {
  .owner = THIS_MODULE,
  .open = hello_proc_open,
  .read = seq_read,
  .write = hello_proc_write,
  .llseek = seq_lseek,
  .release = single_release,
};

static int __init hello_proc_init(void) {
  proc_create("hello_proc", 0666, NULL, &hello_proc_fops);
  return 0;
}

static void __exit hello_proc_exit(void) {
  remove_proc_entry("hello_proc", NULL);
}

MODULE_LICENSE("GPL");
module_init(hello_proc_init);
module_exit(hello_proc_exit);

样例代码注释

功能: 其在/proc目录下创建了hello_proc文件,

echo s >/proc/hello_proc
cat /proc/hello_proc
这样就会有输出信息了。

seq_file 是内核提供的序列接口, 详情就不介绍了,这种方式当数据大的时候内存分配不需要你去关心, 非常实用。

源码地址:qianguozheng

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

钱国正

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值