c - 不同设备的相同设备节点:更改一个节点的值会影响另一个节点 - 如何解决?
问题描述
我有一个关于 Linux 内核设备节点的问题,创建的节点示例在同一个类中,但设备不同,但节点名称相同。如果我改变一个节点的值,另一个节点也会改变:如何防止这种情况发生?
例子:
echo '5' > /sys/class/myclass/mydevice/mydevice
the value of sys/class/myclass/mydevice1/mydevice will also be changed to 5
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sysfs.h>
#include <linux/string.h>
#include <linux/device.h>
#include <linux/fs.h>
static char mybuf[100] = "2";
static int major,major1;
static struct class *myclass;
static ssize_t mydevice_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
return sprintf(buf, "%s\n", mybuf);
}
static ssize_t mydevice_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
sprintf(mybuf, "%s", buf);
return count;
}
static DEVICE_ATTR(mydevice, 0644, mydevice_show, mydevice_store);
static struct file_operations myfops = {
.owner = THIS_MODULE,
};
static int __init mydevice_init(void)
{
int ret;
struct device *mydevice,*mydevice1;
major = register_chrdev(0, "mydevice", &myfops);
if (major < 0) {
ret = major;
return ret;
}
major1 = register_chrdev(0, "mydevice1", &myfops);
if (major1 < 0) {
ret = major1;
return ret;
}
myclass = class_create(THIS_MODULE, "myclass");
if (IS_ERR(myclass)) {
ret = -EBUSY;
goto fail;
}
mydevice = device_create(myclass, NULL, MKDEV(major, 0), NULL, "mydevice");
if (IS_ERR(mydevice)) {
class_destroy(myclass);
ret = -EBUSY;
goto fail;
}
mydevice1 = device_create(myclass, NULL, MKDEV(major1, 0), NULL, "mydevice1");
if (IS_ERR(mydevice1)) {
class_destroy(myclass);
ret = -EBUSY;
goto fail;
}
ret = sysfs_create_file(&mydevice->kobj, &dev_attr_mydevice.attr);
ret = sysfs_create_file(&mydevice1->kobj, &dev_attr_mydevice.attr);
if (ret < 0)
return ret;
return 0;
fail:
unregister_chrdev(major, "mydevice");
return ret;
}
static void __exit mydevice_exit(void)
{
device_destroy(myclass, MKDEV(major, 0));
device_destroy(myclass, MKDEV(major1, 0));
class_destroy(myclass);
unregister_chrdev(major, "mydevice");
unregister_chrdev(major1, "mydevice1");
}
module_init(mydevice_init);
module_exit(mydevice_exit);
MODULE_DESCRIPTION("A simplest driver");
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("HLY");
解决方案
这些设备共享同一个缓冲区。要修复它,请为每个设备使用单独的缓冲区。您可以使用dev_set_drvdata(device, mybuf);
anddev_set_drvdata(device1, mybuf1);
设置指向每个设备的单独缓冲区的指针,并使用dev_get_drvdata(dev)
获取指向设备缓冲区的指针。
推荐阅读
- firebase - 使用 Firebase 从不同的集合中获取数据,并在数据更改时更新 UI
- c# - 如何从 C++ 头文件中检索信息
- c# - WebException 操作在 100 秒后超时 C#
- c# - 正确启动多线程c#执行
- python - Python Telegram Bot 仅适用于我,不适用于其他用户
- angular - 将多个 Firestore 数据库集合调用组合成一个数组
- excel - 将原始 RGBA 文本数据转换为位图图形格式
- c# - 在 uwp 中创建热图覆盖
- c# - 尝试从 ObservableCollection 中删除项目时出错
- angular - 如何在不刷新页面/组件的情况下从 Angular 中的数据库中获取不断变化的数据