c - 如何创建自己的 sysctl 参数

标签 c linux-kernel

在 4.10.0-38-generic 版本中,ctl_table 结构中没有 ctl_name 字段 我找到了教程 https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=2ahUKEwie4Zz_5ZrdAhVKiaYKHRqsDiwQFjABegQICRAC&url=https%3A%2F%2Fsar.informatik.hu-berlin.de%2Fteaching%2F2012-s%2F2012-s%2520Operating%2520Systems%2520Principles%2Flab%2Flab-1%2Fsysctl_.pdf&usg=AOvVaw0mJdbT9E3lP2k3AQOGgzQz

但是还有这个字段的用法

能不能给我一个ctl_table在4.10.0-38-generic版本的使用例子

我尝试实现:

    #include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sysctl.h>

#define SUCCESS (0)


MODULE_LICENSE("GPL");
MODULE_AUTHOR("Kasparyants George");
MODULE_DESCRIPTION("A simple Linux driver");
MODULE_VERSION("0.1");


static int global_var1 = 1;
static int global_var2 = 1;
static int min_val = 0;
static int max_val = 5;
static struct ctl_table_header* header;


static struct ctl_table child_ctl_table[] = {
  {
    .procname = "sample_value1",
    .data = &global_var1,
    .maxlen = sizeof(int),
    .mode = 0644,
    .proc_handler = &proc_dointvec_minmax,
    .extra1 = &min_val,
    .extra2 = &max_val
  }, 
  {
    .procname = "sample_value2",
    .data = &global_var2,
    .maxlen = sizeof(int),
    .mode = 0644,
    .proc_handler = &proc_dointvec_minmax,
    .extra1 = &min_val,
    .extra2 = &max_val
  },
  {}
};


static struct ctl_table parent_ctl_table[] = {
  {
    .procname = "mykernel",
    .mode = 0555,
    .child = child_ctl_table
  }, 
  {}
};


static int __init sysctl_module_init(void) {
  if (!(header = register_sysctl_table(parent_ctl_table))) {
    printk(KERN_ALERT "Error: Failed to register parent_ctl_table\n");
    return -EFAULT;
  }
  printk(KERN_INFO "Start global_var1 = %d, global_var2 = %d\n", global_var1, global_var2);
  return SUCCESS;
}


static void __exit sysctl_module_exit(void) {
  printk(KERN_INFO "End global_var1 = %d, global_var2 = %d\n", global_var1, global_var2);
}


module_init(sysctl_module_init);
module_exit(sysctl_module_exit);

但时有故障。

另外,我还有一个问题: 在内核源代码中,有评论说不推荐使用此参数...为什么?
如果没有此字段,我如何处理参数层次结构? 请帮忙!

最佳答案

修复了我的错误
我们应该在退出函数中取消注册_ctl_table 但是“ child ”字段也有问题......
enter image description here

关于c - 如何创建自己的 sysctl 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52132482/

相关文章:

c - 如何在c中创建结构的新实例

c++ - 当守护线程在后台工作时返回一个函数 (c++)

c - 将 Linux 内核升级到最新的 64 位是否会更改 glibc?

c# - 将结构编码到非托管数组

c - 我的系统调用无法正常工作

linux-kernel - 启动选项 noapic 和 noacpi 实际上有什么作用?

c - 使用系统调用打印文件系统上的所有文件

linux - 如何将 linux 内核和引导加载程序添加到 Raspberry Pi2 的 Ubuntu 14.0.4 核心 rootfs?

c - 程序打印不相关的字符

python - 在 Python 中验证 ctypes 类型精度