字符设备与应用程序的数据交换

字符设备与应用程序的数据交换.


Linux内核——字符设备与应用程序的数据交换.

       在用户空间和内核空间,它们数据交换是不能直接访问的,必须通过内核提供的函数实现数据的交换。

1.将内核空间的数据拷贝到用户空间:copy_to_user原型 见头文件#include <linux/uaccess.h>

copy_to_user
参数说明:
to:用户空间数据的地址
from:内核空间数据的地址
n:要拷贝的字节数

返回值:
0:拷贝成功
非0值:不能被复制的字节数

2.将用户空间的数据拷贝到内核空间:copy_from_user原型 见头文件#include <linux/uaccess.h>
copy_from_user
参数说明:
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;
}


我的GITHUB


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大大棋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值