driver和user之间经常需要数据传输,使用copy_to_user()和copy_from_user()来实现driver到user和user到driver的数据传送。
函数原型:
unsigned
unsigned
代码实例:
hello.c:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <asm/uaccess.h>
MODULE_LICENSE("Dual BSD/GPL");
static int count = 10;
static char *init_mesg = "hello,world\n";
static char *exit_mesg = "goodbye\n";
static int major = 252;
static int minor = 0;
dev_t devnum;
int static hello_dev_open(struct inode *inode, struct file *file)
{
}
int static hello_dev_release(struct inode *inode, struct file *file)
{
}
ssize_t hello_dev_read(struct file *file, char __user *buf,size_t count, loff_t *offset)
{
//使用copy_to_user ()函数从driver读数据到user
}
ssize_t hello_dev_write(struct file *file, const char __user *buf, size_t count, loff_t *offset)
{
//使用copy_from_user()函数从user写数据到driver
}
static struct cdev hello_dev;
static struct file_operations fops ={
};
static int __init hello_init(void)
{
//ret = register_chrdev_region(MKDEV(major,minor), 1, "hello_dev");
}
void hello_exit(void)
{
}
void hello(void)
{
}
module_param(count, int, S_IRUGO);
module_param(init_mesg, charp, S_IRUGO);
module_param(exit_mesg, charp, S_IRUGO);
EXPORT_SYMBOL_GPL(hello);
module_init(hello_init);
module_exit(hello_exit);
测试程序:
main.c:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#define DEVNAME "/dev/hello"
int main()
{
}
编译:gcc
模块加载并创建结点后(过程参考前面日志),运行./main
结果如下:
file /dev/hello is opening……successfully!
Its fd is 3
(输入回车)
write
(输入回车)
read
abcdefghijklmnopqrstuvwx
(输入回车)
输入dmesg命令,结果如下:
file open in hello_dev_open……finished!
ABCDEFGHIJKLMNOPQRSTUVWX
file release in hello_dev_open……finished!