led.c:
#include <linux/module.h> #include <linux/init.h> #include <linux/fs.h> int major = 249; void arm_init(void) { /*操作硬件*/ printk("hello arm init! "); } int led_open(struct inode *inode, struct file *file) { arm_init(); return 0; } struct file_operations led_fops = { .owner = THIS_MODULE, //属于本模块所有 .open = led_open, }; int led_init(void) { int ret; /*模块入口*/ printk("hello kernel "); /*注册字符设备驱动*/ ret = register_chrdev(major,"led-driver",&led_fops); if(ret < 0){ printk("register chrdev led failed "); return -EBUSY; } return 0; } void led_exit(void) { /*模块出口*/ /*注销*/ unregister_chrdev(major,"led-driver"); printk("bye! "); } /*执行insmod 的时候调用module_init*/ module_init(led_init); /*执行 rmmod 的时侯调用module_exit */ module_exit(led_exit); MODULE_DESCRIPTION("this my first drivers"); MODULE_AUTHOR("zhang san feng"); MODULE_LICENSE("GPL"); //许可证 (必须)
app.c:
#include <sys/types.h> #include <stdio.h> #include <sys/stat.h> #include <fcntl.h> int main(int argc,char *argv[]) { int fd; //文件描述符 /*以读的方式打开一个文件,如果文件不存在,则返回错误*/ fd = open("/dev/led",O_RDONLY); if(fd < 0){ perror("open"); return -1; } printf("fd == %d ",fd); return 0; }
Makefile:
obj-m += led.o ################################################ KERNEL = /home/linux-3.0.8-FS210_v9 ROOTFS = /opt/filesystem CROSS_COMPILE = arm-cortex_a8-linux-gnueabi-gcc all: make M=`pwd` -C $(KERNEL) modules $(CROSS_COMPILE) -o app app.c cp led.ko /opt/filesystem/test cp app /opt/filesystem/test cp test.sh /opt/filesystem/test clean: make M=`pwd` -C $(KERNEL) modules clean install: make M=`pwd` -C $(KERNEL) modules_install INSTALL_MOD_PATH=$(ROOTFS)
test.sh:
#/bin/bash insmod led.ko mknod /dev/led c 249 0 ./app