字符设备与应用程序的数据交换.
Linux内核——字符设备与应用程序的数据交换.
在用户空间和内核空间,它们数据交换是不能直接访问的,必须通过内核提供的函数实现数据的交换。
1.将内核空间的数据拷贝到用户空间:copy_to_user原型 见头文件#include <linux/uaccess.h>
参数说明:to:用户空间数据的地址from:内核空间数据的地址n:要拷贝的字节数
返回值:0:拷贝成功非0值:不能被复制的字节数
2.将用户空间的数据拷贝到内核空间:copy_from_user原型 见头文件#include <linux/uaccess.h>
参数说明:to:内核空间数据的地址from:用户空间数据的地址n:要拷贝的字节数
返回值:0:拷贝成功非0值:不能被复制的字节数,也就是有多少个字节没有被成功拷贝
源码.
1.led_dev.c
static ssize_t led_read(struct file *file, char __user *buf, size_t count, loff_t *offset)
{
int ret = 0;
char buff[6]="hello";
//判断当前count是否合法
if(count > sizeof buff)
return -EINVAL; //返回参数无效错误码
//从内核空间拷贝到用户空间
ret = copy_to_user(buf,buff,count);
//获取成功复制的字节数
count = count - ret;
//printk("led_read,buff[%s],count [%d]\n",buf,count);
return count;
}
static ssize_t led_write(struct file *file, const char __user *buf, size_t count, loff_t *offset)
{
int ret = 0;
char buff[1024]={0};
//判断当前count是否合法
if(count > sizeof buff)
return -EINVAL; //返回参数无效错误码
//从用户空间拷贝数据
ret = copy_from_user(buff, buf, count);
//获取成功复制的字节数
count = count - ret;
printk("led_write ,buff[%s], count[%d]\n", buff, count);
return count;
}
2.myled.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv)
{
int fd = 0;
int len = 0;
char buff[1024] = "hello kernel!";
fd = open("/dev/led_dev",O_RDWR);
if(fd < 0)
{
perror("open /dev/led_dev error");
return fd;
}
sleep(2);
write(fd, buff, strlen(buff));
sleep(2);
len = read(fd, buff, 1024);
printf("read len is %d, message:%s\n", len, buff);
close(fd);
return 0;
}
本文探讨了Linux内核中字符设备与应用程序间的数据交换原理,重点介绍了copy_to_user和copy_from_user函数的使用,展示了如何在用户空间和内核空间进行数据传输,并通过实例代码演示了读写操作。
476

被折叠的 条评论
为什么被折叠?



