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