proc_create()内核模块的示例

Rah*_*hul 32 linux-device-driver linux-kernel

有人可以举个proc_create()例子吗?

早些时候他们create_proc_entry()在内核中使用但现在他们正在使用proc_create().

Fre*_*red 36

此示例将创建一个启用读取访问权限的proc条目.我认为你可以通过改变mode传递给函数的参数来启用其他类型的访问.我没有传递父目录,因为没有必要.该结构file_operations是您设置读写回调的地方.

struct proc_dir_entry *proc_file_entry;

static const struct file_operations proc_file_fops = {
 .owner = THIS_MODULE,
 .open  = open_callback,
 .read  = read_callback,
};

int __init init_module(void){
  proc_file_entry = proc_create("proc_file_name", 0, NULL, &proc_file_fops);
  if(proc_file_entry == NULL)
   return -ENOMEM;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

您可以查看此示例以获取更多详细信息:https://www.linux.com/learn/linux-training/37985-the-kernel-newbie-corner-kernel-debugging-using-proc-qsequenceq-files-part-1

  • 您提供的链接已损坏。您能用相关的修复它吗? (2认同)

小智 24

这是一个'hello_proc'代码,它使用了更新的'proc_create()'接口.

#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>

static int hello_proc_show(struct seq_file *m, void *v) {
  seq_printf(m, "Hello proc!\n");
  return 0;
}

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,
  .llseek = seq_lseek,
  .release = single_release,
};

static int __init hello_proc_init(void) {
  proc_create("hello_proc", 0, 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);
Run Code Online (Sandbox Code Playgroud)

此代码取自http://pointer-overloading.blogspot.in/2013/09/linux-creating-entry-in-proc-file.html

  • 这个例子包含[QEMU + Buildroot测试样板](https://github.com/cirosantilli/linux-kernel-module-cheat/blob/4727fadcc8f6e0685f80dc88a2913995a8df01f3/kernel_module/procfs.c). (2认同)

Cof*_*fan 6

此回复只是对@Alhaad Gokhale 精彩答案的更新。从内核 > 5.6 开始,hello world 模块如下所示:

#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>

static int hello_proc_show(struct seq_file *m, void *v) {
  seq_printf(m, "Hello proc!\n");
  return 0;
}

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

static const struct proc_ops hello_proc_fops = {
  .proc_open = hello_proc_open,
  .proc_read = seq_read,
  .proc_lseek = seq_lseek,
  .proc_release = single_release,
};

static int __init hello_proc_init(void) {
  proc_create("hello_proc", 0, 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);
Run Code Online (Sandbox Code Playgroud)

需要注意的主要区别是:

  1. struct proc_ops 取代了 struct file_operations。
  2. 成员名称从 .open、.read 更改为 .proc_open、.proc_read...
  3. 需要删除 .owner 行。

更多信息: