标签:
在linux下的应用层,一切皆文件,每个设备都对应着文件。然而,在内核中,为了标识设备的,会用特意的号码:叫字符号来表示。
今天将会学到字符设备的驱动,来写一个程序,通过在应用层写程序来操作内核里的设备文件,在应用层,写了一个程序,来打开一个文件:
1 #include <stdio.h> 2 #include <fcntl.h> 3 4 int main() 5 { 6 int fd = open("wangcai", O_RDWR); 7 if(fd < 0){ 8 perror("open"); 9 return 1; 10 } 11 } 12 13 ~
在内核层,注册了一个设备文件wangcai和方法ops,注册的时候,将会跳转到my_opreations函数去操作;
1 #include <linux/init.h> 2 #include <linux/thread_info.h> 3 #include <linux/module.h> 4 #include <linux/sched.h> 5 #include <linux/errno.h> 6 #include <linux/kernel.h> 7 #include <linux/module.h> 8 #include <linux/slab.h> 9 #include <linux/input.h> 10 #include <linux/init.h> 11 #include <linux/serio.h> 12 #include <linux/delay.h> 13 #include <linux/clk.h> 14 #include <linux/miscdevice.h> 15 #include <linux/io.h> 16 #include <linux/ioport.h> 17 #include <asm/uaccess.h> 18 #include <linux/irq.h> 19 #include <linux/interrupt.h> 20 #include <linux/cdev.h> 21 22 #include <linux/gpio.h> 23 #include <mach/gpio.h> 24 #include <plat/gpio-cfg.h> 25 26 MODULE_LICENSE("GPL"); 27 MODULE_AUTHOR("bunfly"); 28 29 int my_open(struct inode *no, struct file *fp); 30 //设备号 文件 31 struct file_operations ops; 32 //放法 33 struct cdev wangcai; 34 //设备 35 36 int test_init() 37 { 38 ops.open = my_open; 39 40 //wangcai.ops = &ops; 41 cdev_init(&wangcai, &ops); 42 //字符设备号注册 43 //wangcai.dev = (9, 0); 44 //wangcai.dev = MKDEV(9, 0); 45 //insert_link(&wangcai); 46 cdev_add(&wangcai, MKDEV(9, 0), 1); 47 //将wancai添加到设备 48 return 0; 49 } 50 51 void test_exit() 52 { 53 printk("exit\n"); 54 } 55 56 module_init(test_init); 57 module_exit(test_exit); 58 59 int my_open(struct inode *no, struct file *fp) 60 { 61 printk("zuizui open\n"); 62 return 0; 63 } 64 65
在 APP层,当打开文件的时候,将会发现,屏幕打印了一句:zuizui open!表示;通过了app层的文件操作来读取了一个字符文件。
课后习题:
看懂,会写函数:
1 #include <stdio.h> 2 3 struct file_operations; 4 5 struct person{ 6 int age; 7 char *gf; 8 struct file_operations *ops; 9 //将对象的方法写成一个结构题 10 //方便 11 }; 12 struct file_operations{ 13 void (*fp)(struct person *); 14 }; 15 void eat(struct person *this); 16 int main() 17 { 18 struct file_operations fops; 19 fops.fp = eat; 20 21 struct person tom; 22 tom.age = 20; 23 tom.gf = "lucy"; 24 tom.ops = &fops; 25 //实例化一个对象 26 tom.ops->fp(&tom); 27 } 28 void eat(struct person *this) 29 { 30 printf("please %s\n", this->gf); 31 } 32
2.写下字符文件的read,write,close文件;
3.通过io_control()函数来控制灯亮灯灭。
今天知识大概是这样。有写命令没记下来,等明天在补齐
标签:
原文地址:http://www.cnblogs.com/hongzhunzhun/p/4524756.html