字符设备实验之驱动基本架构

来源:互联网 发布:字体拼音下载软件 编辑:程序博客网 时间:2024/06/05 10:38
#include <linux/module.h>


#include <linux/init.h>
#include <linux/fs.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/sched.h>
#include <linux/pm.h>
#include <linux/slab.h>
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/gpio_keys.h>
#include <linux/workqueue.h>
#include <linux/gpio.h>
#include <asm/io.h>
#include <mach/map.h>
#include <asm/irq.h>
#include <mach/regs-clock.h>
#include <mach/regs-mem.h>
#include <mach/gpio.h>
#include <mach/gpio-smdkc110.h>
#include <mach/regs-gpio.h>




#define DEVICE_NAME "first_drv"
int major;


static int first_drv_open(struct inode *inode, struct file *file)
{
printk("do first_drv_open \n");
return 0;
}


static int first_drv_release(struct inode *inode, struct file *file)
{
printk("do first_drv_release \n");
return 0;
}


static int first_drv_read(struct file *filp, char __user *buff, size_t count, loff_t *offp)
{
printk("do first_drv_close \n");
return 0;
}


static ssize_t first_drv_write(struct file *file, const char __user *buf, size_t count, loff_t * ppos)
{
printk("do first_drv_write \n");
return 0;
}


static struct file_operations first_drv_fops =
{
.owner   = THIS_MODULE, /* 这是一个宏,指向编译模块时自动创建的__this_module 变量*/
.open    = first_drv_open,
.release = first_drv_release,
.read    = first_drv_read,
.write    = first_drv_write,
//.poll    = first_drv_poll,
};


static int __init first_drv_init(void)
{
major = register_chrdev(0, DEVICE_NAME, &first_drv_fops);  //第一个参数为0表示自动分配主设备号

printk("first_drv_init \n");
printk("major = %d \n", major);

return 0;
}


static void __exit first_drv_exit(void)
{
unregister_chrdev(major, DEVICE_NAME);

printk("first_drv_exit \n");
}




module_init(first_drv_init);
module_exit(first_drv_exit);




MODULE_LICENSE("GPL");


测试程序为:



#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>


/* firstdrvtest on
  * firstdrvtest off
  */
int main(int argc, char **argv)
{
int fd;
int val = 1;
fd = open("/dev/xxx", O_RDWR);
if (fd < 0)
{
printf("can't open!\n");
}
/*if (argc != 2)
{
printf("Usage :\n");
printf("%s <on|off>\n", argv[0]);
return 0;
}


if (strcmp(argv[1], "on") == 0)
{
val  = 1;
}
else
{
val = 0;
}*/

write(fd, &val, 4);
return 0;
}

0 0
原创粉丝点击