创建多个设备节点
一次性创建多个设备,共用一个file_operations结构体里的函数
参考代码
#include <linux/init.h>
#include <linux/module.h>
#include <linux/major.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/types.h>
#include <linux/fs.h>
#define TAG "hello"
static int hello_major;
static struct cdev hello_cdev;
static struct class *hello_class;
static ssize_t hello_read(struct file *file, char __user *buffer,
size_t count, loff_t *ppos)
{
printk(TAG" func:%s line:%d\n", __func__, __LINE__);
return count;
}
ssize_t hello_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
printk(TAG" func:%s line:%d\n", __func__, __LINE__);
return count;
}
static int hello_open(struct inode *inode, struct file *file)
{
printk(TAG" func:%s line:%d\n", __func__, __LINE__);
return 0;
}
static int hello_release(struct inode *inode, struct file *file)
{
printk(TAG" func:%s line:%d\n", __func__, __LINE__);
return 0;
}
static const struct file_operations hello_ops = {
.owner = THIS_MODULE,
.read = hello_read,
.write = hello_write,
.open = hello_open,
.release = hello_release,
};
static int hello_init(void)
{
int retval;
dev_t dev_id;
int i;
printk(TAG" func:%s line:%d\n", __func__, __LINE__);
retval = alloc_chrdev_region(&dev_id, 0, 4, "hello"); //0,1
hello_major = MAJOR(dev_id);
printk(TAG"major is %d\n", hello_major);
if (retval < 0) {
printk(TAG"can't get major number\n");
goto error;
}
cdev_init(&hello_cdev, &hello_ops);
retval = cdev_add(&hello_cdev, dev_id, 4); //1
if (retval < 0) {
printk(TAG"cannot add cdev\n");
goto cleanup_alloc_chrdev_region;
}
hello_class = class_create(THIS_MODULE, "hello");
if (IS_ERR(hello_class)) {
printk(TAG "Error creating hello class.\n");
cdev_del(&hello_cdev);
retval = PTR_ERR(hello_class);
goto cleanup_alloc_chrdev_region;
}
for(i = 0; i < 4; i++) {
device_create(hello_class, NULL, MKDEV(hello_major, i), NULL, "hello%d", i);
}
return 0;
cleanup_alloc_chrdev_region:
unregister_chrdev_region(dev_id, 4);
error:
return retval;
}
static void hello_exit(void)
{
int i;
dev_t dev_id = MKDEV(hello_major, 0);
class_destroy(hello_class);
for(i = 0; i < 4; i++) {
device_destroy(hello_class, MKDEV(hello_major, i));
}
cdev_del(&hello_cdev);
unregister_chrdev_region(dev_id, 4);
printk(TAG" func:%s line:%d\n", __func__, __LINE__);
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
测试程序
int main(int argc, char **argv)
{
int fd;
char buf = '1';
if(argc != 2) {
printf("Usage: %s [node]\n", argv[0]);
exit(1);
}
fd = open(argv[1], O_RDWR);
if (fd < 0) {
printf("open %s failed\n", argv[1]);
}
write(fd, &buf, 1);
read(fd, &buf, 1);
close(fd);
return 0;
}
编译好测试程序,假如编译好的程序名为testhello,push到机器里,运行
./testhello /dev/hello0
./testhello /dev/hello1
./testhello /dev/hello2
./testhello /dev/hello3
观察log,可以看出, /dev/hello0~3的节点都会调用到驱动file_operations结构体里对应的函数
问题
这些设备都是虚拟的设备,如何操作真实的设备?