- #include <linux/init.h>
- #include <linux/kernel.h>
- #include <linux/module.h>
- #include <linux/types.h>
- #include <linux/fs.h>
- #include <linux/mm.h>
- #include <linux/errno.h>
- #include <asm/segment.h>
- #include <linux/module.h>
- #include <linux/sched.h>
- #include <linux/cdev.h>
- MODULE_LICENSE("Dual BSD/GPL");
- unsigned int test_major=0;
- static char *book_name = "dissecting Linux Device Drviver";
- static int num = 4000;
- static int global_major = 0;
- struct cc_dev_t
- {
- struct cdev cdev;
- } cc_dev;
- static int cc_read(struct inode *inode,struct file *file,char *buf,int count)
- {
- printk(KERN_INFO "*******cc_read********\n");
- return 0;
- }
- static int cc_write(struct inode *inode,struct file *file,const char *buf,int count)
- {
- printk(KERN_INFO "*******cc_write*******\n");
- return 0;
- }
- static int cc_open(struct inode *inode,struct file *file)
- {
- printk(KERN_INFO "********cc_open*******\n");
- return 0;
- }
- static void cc_release(struct inode *inode,struct file *file)
- {
- printk(KERN_INFO "*******cc_release*****\n");
- }
- struct file_operations cc_fops={
- .owner = THIS_MODULE,
- .read = cc_read,
- .write = cc_write,
- .open = cc_open,
- .release = cc_release,
- };
- static int __init cc_init(void)
- {
- int result,err;
- dev_t devno = MKDEV(0,0);
- result = alloc_chrdev_region(&devno,0,1,"cc");
- global_major = MAJOR(devno);
- if(result < 0)
- {
- return result;
- }
- cdev_init(&cc_dev.cdev,&cc_fops);
- err = cdev_add(&cc_dev.cdev,devno,1);
- if(err)
- printk(KERN_NOTICE "Error");
- return 0;
- }
- void cc_exit(void)
- {
- cdev_del(&cc_dev.cdev);
- unregister_chrdev_region(MKDEV(global_major,0),1);
- }
- module_init(cc_init);
- module_exit(cc_exit);
- module_param(num,int,S_IRUGO);
- module_param(book_name,charp,S_IRUGO);
- MODULE_AUTHOR("xyl");
- MODULE_DESCRIPTION("A simple Hello world Moudle");
- MODULE_ALIAS("a simplest moudle");
写完驱动部分 make一下 在/proc/devices下面就会有对应的主设备号了
makefile文件
- PWD = $(shell pwd)
- CC=gcc
- KERNEL_SRC = /usr/src/linux-source-2.6.38/
- obj-m := cc.o
- module-objs := cc.o
- all:
- $(MAKE) -C $(KERNEL_SRC) M=$(PWD) modules
- clean:
- rm *.ko
- rm *.o
之后在/dev下面创建设备节点 cat /proc/devices获得主设备号 mknod /dev/cc c major minor
在/dev下面就会有对应的设备节点了 如果想要删除的话直接rm掉
下面是test.c
- #include<stdio.h>
- #include<fcntl.h>
- int main()
- {
- int myfile;
- char buffer[100];
- int retval;
- myfile = open("/dev/cc",O_RDWR);
- if(myfile < 0)
- printf("Open filed /n");
- write(myfile,"hello_world",sizeof("hello_world"));
- retval = read(myfile,buffer,100);
- buffer[retval] = 1;
- printf("redponse:%s/n",buffer);
- close(myfile);
- }
其中close对应驱动中的release.上面的 write read 内容就随便写啦,因为我驱动中并没有实现。
编译一下执行,看内核输出信息dmesg 如下
[ 5096.422497] ********cc_open*******
[ 5096.422512] *******cc_write*******
[ 5096.422519] *******cc_read********
[ 5096.422572] *******cc_release*****
这样就说明调用成功了