驱动文件:qudong.c,make生成qudong.ko文件,烧录到ARM板上
#include<linux/init.h> #include<linux/module.h> #include<linux/kernel.h> #include <linux/poll.h> /* COPY_TO_USER */ #include<linux/errno.h> #define DEV_NAME "rwtest" static int major=0; static int MAX_BUF_LEN=1024; static char drv_buf[1024]; static int WRI_LENGTH=0; /************************************写入*************************************************/ static ssize_t dx_write(struct file *file, const char __user *buffer, size_t count, loff_t * ppos) { if(count > MAX_BUF_LEN)count = MAX_BUF_LEN; copy_from_user(drv_buf , buffer, count); WRI_LENGTH = count; printk("write data to driver "); return count; } /**************************************读取***********************************************/ static ssize_t dx_read(struct file *filp, char __user *buffer, size_t count, loff_t *ppos) { int i=0,j=0; if(count > MAX_BUF_LEN) count=MAX_BUF_LEN; for(i=strlen(drv_buf);i>0;i--) { buffer[j]=drv_buf[i-1]; j++; } //copy_to_user(buffer,drv_buf,count); printk("read data from driver "); return count; } //===========================打开========================================= static int dx_open(struct inode *inode, struct file *filp) { printk("device open sucess! "); return 0; } /**********************************release***************************************************/ static int dx_release(struct inode *inode, struct file *filp) { printk("device release "); return 0; } //======================结构体,驱动各属性================================================== static struct file_operations file_opt = { owner: THIS_MODULE, write: dx_write, read: dx_read, open: dx_open, release:dx_release, }; //---------------------------------------------------------------------- static int __init qudong_init(void) { int ret; ret = register_chrdev(0, DEV_NAME, &file_opt); if(ret<0) { printk(DEV_NAME " can't get major number "); return 0; } major=ret; printk("dx module major number is %d ", ret); return 0; } //----------------------------------------------------------------------- static void __exit qudong_exit(void) { unregister_chrdev(major,DEV_NAME); printk("exit "); } module_init(qudong_init); module_exit(qudong_exit); MODULE_LICENSE("GPL");
Makefile文件:
## Makefile template. obj-m := qudong.o UNAME := $(shell uname -r) PWD := $(shell pwd) ADVMOD := qudong defualt: @make -C /lib/modules/$(UNAME)/build SUBDIRS=$(PWD) modules clean: @rm -f *.o @rm -f *.ko @rm -f *.mod.c @rm -f .*.cmd @rm -rf .tmp_versions #endif
或者ARM下的Makefile文件:
ifneq ($(KERNELRELEASE),) obj-m := hello.o else KDIR := /usr/src/linux2.6.28 all: make -C $(KDIR) M=$(PWD) modules ARCH=arm CROSS_COMPILE=arm-linux- clean: rm -f *.ko *.o *.mod.o *.mod.c *.symvers modul* endif
测试程序如下:
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include<string.h> int main() { int fd=0; int ret=0; char bufw[100]={'