Linux字符设备-自动创建设备号和设备节点
先写一个自动分配字符设备号和设备节点的例子及APP
手动安装步骤:
Insmod my_char_dev.ko
不需要再安装设备节点
然后是测试app
./my_char_dev_app 1
#include <linux/module.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/fs.h>
#include <asm/device.h> //下面这三个头文件是由于动态创建需要加的
#include <linux/device.h>
#include <linux/cdev.h>
#include “my_cdev.h”
struct cdev cdev;
dev_t devno;//这里是动态分配设备号和动态创建设备结点需要用到的
struct class *cdev_class;
int my_cdev_open(struct inode *node,struct file *filp)
{
printk(“my_cdev_open sucess!\n”);
return 0;
}
long my_cdev_ioctl(struct file *filp ,unsigned int cmd ,unsigned long arg)
{
switch(cmd)
{
case LED_ON:
printk(“LED_ON is set!\n”);
return 0;
case LED_OFF:
printk(“LED_OFF is set!\n”);
return 0;
default :
return -EINVAL;
}
}
struct file_operations my_cdev_fops=
{
.open = my_cdev_open,
.unlocked_ioctl = my_cdev_ioctl,
};
static int my_cdev_init(void)
{
int ret;
/**动态分配设备号*/
ret = alloc_chrdev_region(&devno,0,1,”my_chardev”);
if(ret)
{
printk(“alloc_chrdev_region fail!\n”);
unregister_chrdev_region(devno,1);
return ret;
}
else
{
printk(“alloc_chrdev_region sucess!\n”);
}
/**描述结构初始化*/
cdev_init(&cdev,&my_cdev_fops);
/**描述结构注册*/
ret = cdev_add(&cdev,devno,1);
if(ret)
{
printk(“cdev add fail.\n”);
unregister_chrdev_region(devno,1);
return ret;
}
else
{
printk(“cdev add sucess!\n”);
}
cdev_class = class_create(THIS_MODULE,”my_chardev”);
if(IS_ERR(cdev_class))
{
printk(“Create class fail!\n”);
unregister_chrdev_region(devno,1);
return -1;
}
else
{
printk(“Create class sucess!\n”);
}
device_create(cdev_class,NULL,devno,0,”my_chardev”);
return 0;
}
static void my_cdev_exit(void)
{
device_destroy(cdev_class,devno);
class_destroy(cdev_class);
cdev_del(&cdev);
unregister_chrdev_region(devno,1);
printk(“my_cdev_exit sucess!\n”);
}
module_init(my_cdev_init);
module_exit(my_cdev_exit);
MODULE_LICENSE(“GPL”);
MODULE_AUTHOR(“YEFEI”);
MODULE_DESCRIPTION(“YEFEI Driver”);
—————————————
#ifndef __MY_CDEV_H__
#define __MY_CDEV_H__
#define LED_MAGIC ‘L’
#define LED_ON _IO(LED_MAGIC,0)
#define LED_OFF _IO(LED_MAGIC,1)
#endif
—————————————
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <stdio.h>
#include “my_cdev.h”
int main(int argc,char *argv[])
{
int fd;
int cmd;
if(argc < 2)
{
printf(“Please enter secend param!\n”);
return 0;
}
cmd = atoi(argv[1]);
fd = open(“/dev/my_chardev”,O_RDWR);
if(fd < 0)
{
printf(“Open dev/my_chardev fail!\n”);
close(fd);
return 0;
}
switch(cmd)
{
case 1:
ioctl(fd,LED_ON);
break;
case 2:
ioctl(fd,LED_OFF);
break;
default:
break;
}
close(fd);
return 0;
}
——————————-
1 obj-m := my_char_dev.o
2 KDIR := /home/win/dn377org/trunk/bcm7252/linux/
3 all:
4 make -C $(KDIR) M=$(PWD) modules CROSS_COMPILE=arm-linux- ARCH=arm
5 clean:
6 rm -f *.ko *.o *.mod.o *.mod.c *.symvers *.bak *.order
本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-02/128600.htm