kernel模块参数的一点思考

如果模块需要带参数,可参考

static unsigned int pcm_debug = 0;
module_param(pcm_debug, int, 0644);
MODULE_PARM_DESC(pcm_debug, "enable debug messages for pcm");

 运行个驱动看看

#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <linux/errno.h>
#include <linux/device.h>
#include <linux/miscdevice.h>
#include<linux/slab.h>

static unsigned int pcm_debug = 0;
module_param(pcm_debug, int, 0644);
MODULE_PARM_DESC(pcm_debug, "enable debug messages for pcm");

ssize_t sys_read(struct device *dev, struct device_attribute *attr, char *buf)
{
	printk("pcm_debug=%d\n", pcm_debug);
	return 0;
}

ssize_t sys_write(struct device * dev, struct device_attribute * attr,
		  const char *buf, size_t count)
{
	unsigned channel = 0;
	int ret;
	ret = sscanf(buf, "%d", &channel);
	if (ret > 0) {
		printk("channel=%d\n", channel);
		return strlen(buf);
	}
	return -EINVAL;
}

static DEVICE_ATTR(test, 0664, sys_read, sys_write);

int test_open(struct inode *node, struct file *filp)
{
	return 0;
}

int test_close(struct inode *node, struct file *filp)
{
	return 0;
}

struct file_operations test_fops = {
	.open = test_open,
	.release = test_close,
};

static struct miscdevice test_dev = {
	.minor = MISC_DYNAMIC_MINOR,
	.name = "test",
	.fops = &test_fops,
};

static int __init test_init(void)
{
	int ret;
	printk("test_init\n");
	ret = misc_register(&test_dev);
	if (ret != 0) {
		pr_err("cannot register miscdev\n");
	}
	device_create_file(test_dev.this_device, &dev_attr_test);
	return 0;
}

static void __exit test_exit(void)
{
	printk("test_exit\n");
	misc_deregister(&test_dev);
}

module_init(test_init);
module_exit(test_exit);
MODULE_LICENSE("GPL v2");

如果我们要动态修改变量的值,比较常见的是模块参数或者sys接口,从偷懒的角度看,模块参数代码少,sys接口功能更齐全。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值