driverdemo.c
- #include <linux/module.h>
- #include <linux/init.h>
- #include <linux/types.h>
- #include <linux/fs.h>
- #include <linux/mm.h>
- #include <linux/cdev.h>
- #include <linux/errno.h>
- #include <linux/sched.h>
- #include <asm/io.h>
- #include <asm/system.h>
- #include <asm/uaccess.h>
- #define simple_MAJOR 200
- static unsigned char simple_inc=0;
- static char demoBuffer[256];
- int simple_open(struct inode *inode,struct file *filp){
- if(simple_inc>0) return -ERESTARTSYS;
- simple_inc++;
- return 0;
- }
- int simple_release(struct inode *inode,struct file *filp){
- simple_inc--;
- return 0;
- }
- ssize_t simple_read(struct file *filp,char __user *buf,size_t count,loff_t *f_pos){
- if(copy_to_user(buf,demoBuffer,count)){
- count=-EFAULT;
- }
- return count;
- }
-
- size_t simple_write(struct file *file,const char __user *buf,size_t count,loff_t *f_pos){
- if (copy_from_user(demoBuffer + *f_pos,buf,count)){
- count = -EFAULT;
- }
- return count;
- }
-
- void simple_cleanup_module(void){
- unregister_chrdev(simple_MAJOR,"simple");
- printk("simple_cleanup_module!\n");
-
- }
-
- static const struct file_operations simple_fops={
- .owner=THIS_MODULE,
- .open=simple_open,
- .release=simple_release,
- .read=simple_read,
- .write=simple_write,
- };
-
- int simple_init_module(void){
- int ret;
- ret=register_chrdev(simple_MAJOR,"simple",&simple_fops);
- if(ret<0){
- printk("Unable to register character device %d!/n",simple_MAJOR);
- return ret;
- }
- return 0;
- }
-
- module_init(simple_init_module);
- module_exit(simple_cleanup_module);
-
- MODULE_LICENSE("Dual BSD/GPL");
Makefile 文件
- ifeq ($(KERNELRELEASE),)
- KERNELDIR ?=/usr/src/linux-2.6.29.4
- INCLUDE ?=./
- PWD :=$(shell pwd)
- modules:
- $(MAKE) -C $(KERNELDIR) -I $(INCLUDE) M=$(PWD) modules
- modules_install:
- $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install
- clean:
- rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions
- else
- obj-m :=driverdemo.o
- endif
生成安装驱动
- make //会生成driverdemo.ko文件
- insmod driverdemo.ko //安装到系统内 需要在root 下运行
创建设备文件
这里我们只要关心200是什么, 200为设备号,也需要在root 下运行
我们在前面代码里
这就是设备号
应用程序code
test.c
- #include <stdio.h>
- #include <fcntl.h>
- int main(void){
- int fd;
- int i;
- char data[256];
- int retval;
- fd=open("/dev/fgj",O_RDWR);
- if(fd==-1){
- perror("error open\n");
- exit(-1);
- }
- printf("open /dev/fgj successfully\n");
-
- retval=write(fd,"http://blog.csdn.net/ssihc0",26);
- if(retval==-1){
- perror("write error \n");
- exit(-1);
- }
-
- retval=read(fd,data,26);
- if(retval==-1){
- perror("read error\n");
- exit(-1);
- }
- data[retval]=0;
- printf("read successfully:%s\n",data);
- close(fd);
- return 0;
-
- }
生成
运行./a.out
open /dev/fgj successfully
read successfully:http://blog.csdn.NET/ssihc0
下面是一些我们在驱动开发过程经常要用到的COMMAND
- history
- cat /var/log/messages | tail
-
- mknod /dev/fgj c 200 0
-
- cat /proc/modules | grep d*
-
- insmod driverdemo.ko
- rmmod 1-2module.ko
-
- ismod
-
- dmesg | tail
-
- insmod test.ko a=3 b=2 AddOrSub=2