O06 - proc

本文介绍了一个使用Proc文件系统进行读写配置的例子。通过创建一个名为test_rw的可读写节点,用户可以在运行时修改内核中的变量,并且能够读取这个变量的当前值。该示例适用于Linux内核版本3.10之前和之后的不同实现。

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

通过proc文件系统配置


#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/version.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>

static unsigned int variable;
static struct proc_dir_entry *test_dir, *test_entry;

#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 10, 0)
static int test_proc_read(char *buf, char **start, off_t off, int count,
		int *eof, void *data)
{
	unsigned int *ptr_var = data;
	return sprintf(buf, "test_rw = %u\n", *ptr_var);
}

static int test_proc_write(struct file *file, const char *buffer,
		unsigned long count, void *data)
{
	unsigned int *ptr_var = data;

	*ptr_var = simple_strtoul(buffer, NULL, 10);

	return count;
}
#else
static int test_proc_show(struct seq_file *seq, void *v)
{
	unsigned int *ptr_var = seq->private;
	seq_printf(seq, "%u\n", *ptr_var);
	return 0;
}

static ssize_t test_proc_write(struct file *file, const char __user *buffer,
		size_t count, loff_t *ppos)
{
	struct seq_file *seq = file->private_data;
	unsigned int *ptr_var = seq->private;

	*ptr_var = simple_strtoul(buffer, NULL, 10);
	return count;
}

static int test_proc_open(struct inode *inode, struct file *file)
{
	return single_open(file, test_proc_show, PDE_DATA(inode));
}

static const struct file_operations test_proc_fops =
{
	.owner = THIS_MODULE,
	.open = test_proc_open,
	.read = seq_read,
	.write = test_proc_write,
	.llseek = seq_lseek,
	.release = single_release,
};
#endif

static __init int test_proc_init(void)
{
	test_dir = proc_mkdir("test_dir", NULL);
	if (test_dir) {
#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 10, 0)
		test_entry = create_proc_entry("test_rw", 0666, test_dir);
		if (test_entry) {
			test_entry->nlink = 1;
			test_entry->data = &variable;
			test_entry->read_proc = test_proc_read;
			test_entry->write_proc = test_proc_write;
			return 0;
		}
#else
	test_entry = proc_create_data("test_rw",0666, test_dir, &test_proc_fops, &variable);
	if (test_entry)
		return 0;
#endif
	}

	return -ENOMEM;
}
module_init(test_proc_init);

static __exit void test_proc_cleanup(void)
{
	remove_proc_entry("test_rw", test_dir);
	remove_proc_entry("test_dir", NULL);
}
module_exit(test_proc_cleanup);

MODULE_AUTHOR("Barry Song <baohua@kernel.org>");
MODULE_DESCRIPTION("proc exmaple");
MODULE_LICENSE("GPL v2");



#Makefile
#
#
KVERS = $(shell uname -r)

# Kernel modules
obj-m += proc.o

# Specify flags for the module compilation.
#EXTRA_CFLAGS=-g -O0

build: kernel_modules

kernel_modules:
	make -C /lib/modules/$(KVERS)/build M=$(CURDIR) modules

clean:
	make -C /lib/modules/$(KVERS)/build M=$(CURDIR) clean



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值