虚拟字符驱动函数的实现

来源:互联网 发布:我知你好未再妈妈网 编辑:程序博客网 时间:2024/05/14 05:59

根据网友的模版改写的虚拟字符驱动函数的实现,可以实现应用程序数据写入驱动程序所在内核空间,以及读出功能。可作为驱动函数初学的参考

以下是驱动程序代码

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <asm/uaccess.h> /* copy_to_user,copy_from_user */
#define MY_MAJOR 240


static unsigned char buffer[1024];


int my_open (struct inode *inode,struct file *filp)
{
printk("#########open######\n");
return 0;
}


ssize_t my_read (struct file *filp, char __user *buf, size_t count,loff_t *f_pos)
{
if(count>1024)
return 0;
copy_to_user(buf,buffer,count);
//printk("%s %s",buffer,buf);
printk("#########read###### count:%d\n",(int)count);
return count;
}


ssize_t my_write (struct file *filp, const char __user *buf, size_t count,loff_t *f_pos)
{
if(count>1024)
return 0;
copy_from_user(buffer,buf,count);
//printk("%s %s",buffer,buf);
printk("#########write###### count:%d\n",(int)count);
return count;
}


int my_release (struct inode *inode, struct file *filp)
{
printk("#########release######\n");
return 0;
}


struct file_operations my_fops ={
.owner = THIS_MODULE,
.open = my_open,
.read = my_read,
.write = my_write,
.release = my_release,
};


int __init my_init (void)
{
int rc;
printk ("Test char dev\n");
rc = register_chrdev(MY_MAJOR,"my",&my_fops);
if (rc <0)
{
printk ("register %s char dev error\n","my");
return -1;
}


printk ("ok!\n");
return 0;
}


void __exit my_exit (void)
{
unregister_chrdev(MY_MAJOR,"my");
printk ("module exit\n");
}


MODULE_LICENSE("GPL");
module_init(my_init);
module_exit(my_exit);

以下是Makefile文件 其中 /home/daiyinger/soft/linux-3.0.1/ 是我的内核代码目录

obj-m := driver_char.o
KDIR := /home/daiyinger/soft/linux-3.0.1/
all:
make -C $(KDIR) M=$(shell pwd) modules
install:
cp driver_char.ko /tftpboot/
clean:
make -C $(KDIR) M=$(shell pwd) clean

把以上代码拷贝到linux目录下执行make

再把生成的driver_char.ko文件拷到开发板目录下


执行 insmod driver_char.ko


执行lsmod可以查看模块是否加载成功

执行mknod /dev/my_char c 240 0 创建设备文件访问节点

应用程序代码如下

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main (void)
{
int fd;
int i;
char buf[10]="hello!\n";
int count=0;
char buf2[10]={0};
fd = open("/dev/my_char",O_RDWR);
if (fd < 0)
{
printf ("Open /dev/my_char");
return -1;
}
count=strlen(buf);
write(fd,buf,count);
read(fd,buf2,count);
printf("count %d \n",count);
printf("%s \n",buf2);
close (fd);
return 0;
}

执行 arm-linux-gcc driver_char_app.c -o driver_char_app 生成可执行文件拷贝到开发板目录下

执行./driver_char_app 



[root@FORLINX6410]# mknod /dev/my_char c 240 0
[root@FORLINX6410]# cd /usr/bin/
[root@FORLINX6410]# ./driver_char_app
count 7
hello!



原创粉丝点击