内存虚拟字符设备驱动,但是其中的read,write有问题
#include <linux/module.h>#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/malloc.h>
#include <asm/uaccess.h>
#include <asm/page.h>
#include <linux/errno.h>
#include <linux/config.h>
char c_req;
static trace_major=0;
ssize_t trace_read(struct file *filp,char *buf,size_t count,loff_t *f_pos);
static ssize_t trace_write(struct file *filp,const char *buf,size_t count,loff
_t *ppos);
int trace_open(struct inode *inode,struct file *filp);
int trace_release(struct inode *inode,struct file *filp);
struct file_operations trace_ops={
open: trace_open,
read: trace_read,
write:trace_write,
release:trace_release,
};
ssize_t trace_read(struct file *filp,char *buf,size_t count,loff_t *f_pos)
{
int length=strlen(c_req);
if(count>99) count=99;
count=length-*f_pos;
if(copy_to_user(buf,c_req,count))
{
printk("error reading,copy_to_user\n");
return -EFAULT;
}
*f_pos+=count;
return count;
}
static ssize_t trace_write(struct file *filp,const char *buf,size_t count,loff
_t *ppos)
{
int num;
num=count<100?count:100;
if(copy_from_user(c_req,buf,num))
return -EFAULT;
printk("Trace_driver succed!\n");
return num;
}
int trace_open(struct inode *inode,struct file *filp)
{
filp->f_op=&trace_ops;
printk("open success!\n");
MOD_INC_USE_COUNT;
return 0;
}
int trace_release(struct inode *inode,struct file *filp)
{
MOD_DEC_USE_COUNT;
return 0;
}
int init_module(void)
{
int result;
printk("initing......\n");
result=register_chrdev(trace_major,"trace",&trace_ops);
printk("Major is %d!\n",result);
strcpy(c_req,"Hello,please write anything to trace!\n");
printk("Success in getting buffer!\n");
printk("%s\n",c_req);
return 0;
}
void cleanup_module(void)
{
unregister_chrdev(trace_major,"trace");
printk("exiting......\n");
}
我用gcc -c trace.c -D_KERNEL_ -DMODULE -O2 -I/usr/src/linux-*.*.*/include -g -Wall -o trace.o编译也通过了,而且加载模块也成功了,然后用mknod /dev/trace 254 0注册文件系统成功。用cat也能正确显示:Hello,please write anything to trace!
但问题是我在用户空间用fread,fwrite以及其它一些文件读写函数调用为什么没反映?往里写的话更本不调用trace_write这个函数。但是我用cat file>/dev/trace确可以正常写入,用cat也能正常读取,这是为何? 但问题是我在用户空间用fread,fwrite以及其它一些文件读写函数调用为什么没反映?
这个是什么意思?
页:
[1]