如果模块需要带参数,可参考
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接口功能更齐全。