Skip to content

Instantly share code, notes, and snippets.

@furandon-pig
Created December 16, 2018 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save furandon-pig/571a4afaefe7a8386a4392bdc0a3f84c to your computer and use it in GitHub Desktop.
Save furandon-pig/571a4afaefe7a8386a4392bdc0a3f84c to your computer and use it in GitHub Desktop.
Linux-4.19.9でのカーネルモジュール作成サンプル。
/*
* hello.c - kernel module sample with sysctl value
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/seq_file.h>
static struct ctl_table_header *hello_sysctl_header;
static int value;
module_param(value, int, 0);
static struct hello_sysctl_settings {
int value;
} hello_sysctl_settings;
// "sysctl -w hello.value=<N>" や "cat /proc/sys/hello/value" 時に呼ばれる。
// 書き換えられた値に対して処理を行う場合は、この関数内で処理する。
static int hello_sysctl_handler(struct ctl_table *ctl, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
int ret = proc_dointvec(ctl, write, buffer, lenp, ppos);
printk("-=> hello_sysctl_handler()\n");
if (write) {
if (hello_sysctl_settings.value == 777) {
printk(" (^_^)/\n");
}
}
return ret;
}
// /proc/sys/hello/value のprocfsを設定する。
static struct ctl_table hello_table[] = {
{
.procname = "value",
.data = &hello_sysctl_settings.value,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = hello_sysctl_handler,
},
{ }
};
static struct ctl_table hello_root_table[] = {
{
.procname = "hello",
.maxlen = 0,
.mode = 0555,
.child = hello_table,
},
{ }
};
// sysctl変数の登録。
static void hello_sysctl_register(void)
{
static int initialized;
printk("-=> hello_sysctl_register()\n");
if (initialized == 1)
return;
hello_sysctl_header = register_sysctl_table(hello_root_table);
hello_sysctl_settings.value = 0; // 初期値の設定
initialized = 1;
}
static void hello_sysctl_unregister(void)
{
printk("-=> hello_sysctl_unregister()\n");
if (hello_sysctl_header)
unregister_sysctl_table(hello_sysctl_header);
}
static int hello_init(void)
{
printk("-=> hello_init()\n");
hello_sysctl_register();
return 0;
}
static void hello_exit(void)
{
printk("-=> hello_exit()\n");
hello_sysctl_unregister();
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_INFO(hello, "Y");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment