标签:oid struct name ops ror argc 应用 erro author
linux系统将设备分为3类:字符设备、块设备、网络设备。
设备驱动程序
1 #include <linux/module.h> 2 #include <linux/kernel.h> 3 #include <linux/fs.h> 4 #include <linux/init.h> 5 #include <linux/delay.h> 6 #include <asm/irq.h> 7 #include <mach/regs-gpio.h> 8 #include <mach/hardware.h> 9 #include <linux/device.h> 10 #include <linux/gpio.h> 11 12 #define DEVICE_NAME "mydriver"
13 static int MYDRIVER_Major = 0; 14 15 static int mydriver_open(struct inode *inode, struct file *file) 16 { 17 printk("My Driver Open Called!\n"); 18 return 0; 19 } 20 21 static int mydriver_release(struct inode *inode, struct file *file) 22 { 23 printk("My Driver Release Called!\n"); 24 return 0; 25 } 26 27 static int mydriver_read(struct file *filp, char *buf, size_t count, loff_t *f_pos) 28 { 29 printk("My Driver Read Called!\n"); 30 return 0; 31 } 32 33 static int mydriver_write(struct file *filp, char *buf, size_t count, loff_t *f_pos) 34 { 35 printk("My Driver Write Called!\n"); 36 return 0; 37 } 38 39 static int mydriver_ioctl( struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg) 40 { 41 42 } 43 44 static struct file_operations mydriver_fops = 45 { 46 .owner = THIS_MODULE, 47 .open = mydriver_open, 48 .release = mydriver_release, 49 .read = mydriver_read, 50 .write = mydriver_write, 51 .ioctl = mydriver_ioctl, 52 }; 53 54 static struct class *mydriver_class; 55 56 static int __init mydriver_init(void) 57 { 58 59 printk("MY DRIVER MODULE INIT\n"); 60 61 MYDRIVER_Major = register_chrdev(0, DEVICE_NAME, &mydriver_fops); 62 if (MYDRIVER_Major < 0) 63 { 64 printk(DEVICE_NAME " can‘t register major number\n"); 65 return MYDRIVER_Major; 66 } 67 printk("register My Driver OK! Major = %d\n", MYDRIVER_Major); 68 69 //注册一个类,使mdev可以在"/dev/"目录下面建立设备节点 70 mydriver_class = class_create(THIS_MODULE, DEVICE_NAME); 71 if(IS_ERR(mydriver_class)) 72 { 73 printk("Err: failed in My Driver class. \n"); 74 return -1; 75 } 76 //创建一个设备节点,节点名为DEVICE_NAME 77 device_create(mydriver_class, NULL, MKDEV(MYDRIVER_Major, 0), NULL, DEVICE_NAME); 78 79 printk(DEVICE_NAME " initialized\n"); 80 return 0; 81 } 82 83 static void __exit mydriver_exit(void) 84 { 85 printk("MY DRIVER MODULE EXIT\n"); 86 unregister_chrdev(MYDRIVER_Major, DEVICE_NAME); 87 device_destroy(mydriver_class, MKDEV(MYDRIVER_Major, 0)); 88 class_destroy(mydriver_class); 89 } 90 91 module_init(mydriver_init); 92 module_exit(mydriver_exit); 93 94 MODULE_AUTHOR("www.txmcu.com"); 95 MODULE_DESCRIPTION("My Driver"); 96 MODULE_LICENSE("GPL");
测试应用程序
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <sys/ioctl.h> 5 6 int main(int argc, char **argv) 7 { 8 int fd; 9 fd = open("/dev/XXXX", 0); 10 if (fd < 0) 11 { 12 perror("open device"); 13 exit(1); 14 } 15 16 /*your code*/ 17 18 close(fd); 19 return 0; 20 }
标签:oid struct name ops ror argc 应用 erro author
原文地址:https://www.cnblogs.com/yl103387239/p/9308851.html