程序案例:(关键出已用颜色标出)
#include <linux/module.h> #include <linux/kernel.h> #include <asm/io.h> #include <linux/fs.h> #include <asm/uaccess.h> #include <linux/device.h> #define GPM4CON 0x110002e0 #define GPM4DAT 0x110002e4 static unsigned long* ledcon = NULL; static unsigned long* leddat = NULL; // write(int fd, void* buf, int count); static ssize_t led_write(struct file * filp, const char __user * buff, size_t count, loff_t * offet) { char buf[32] = {0}; int ret = 0; ret = copy_from_user(buf, buff, min(count, sizeof(buf))); if(strncmp(buf, "led on", strlen("led on")) == 0) { *leddat &= 0xf0; } else if(strncmp(buf, "led off", strlen("led off")) == 0) { *leddat |= 0x0f; } else { printk("***cmd error!***\n"); } return min(count, sizeof(buf)); } //文件操作集合定义初始化。 给上层应用层留操作接口 static struct file_operations g_tfops = { .owner = THIS_MODULE, .write = led_write, }; static int g_major = 0; static struct class * g_ptclass = NULL; static int __init pyw_module_init(void) { printk("hello module! 你好\n"); ledcon = ioremap(GPM4CON, 4); leddat = ioremap(GPM4DAT, 4); *ledcon &= 0xffff0000; *ledcon |= 0x00001111; *leddat |= 0x0f; g_major = register_chrdev(0, "led_xxx", &g_tfops); printk("major = %d\n", g_major); g_ptclass = class_create(THIS_MODULE, "pyw"); //在文件系统中创建一个类目录,用来管理设备节点文件 device_create(g_ptclass, NULL, MKDEV(g_major, 0), NULL, "led_auto"); //根据设备号, 在文件系统中创建设备节点文件 return 0; } static void __exit pyw_module_exit(void) { device_destroy(g_ptclass, MKDEV(g_major, 0)); class_destroy(g_ptclass); printk("byebye %s\n", "module"); unregister_chrdev(g_major, "led_xxx"); *leddat |= 0x0f; iounmap(ledcon); iounmap(leddat); } module_init(pyw_module_init); module_exit(pyw_module_exit); |