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");
}
return 0;
}
static void my_cdev_exit(void)
{
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");
APP头文件my_cdev.h
#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
APP测试文件my_char_dev_app.c
#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;
}