字符設備與應用程序的數據交換.
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;
}