例如:char buf[128] = “i am huyue”;---->用户空间
要求:在内核中将字符数组的内容进行打印 ---->通过dmesg命令,可以查看到信息
命令码封装:#define UACCESS_BUF _IOW(‘a’,1,char [128])
.h
#define UACCESS_BUF _IOW('a',1,char[128])
.c
long myioctl(struct file*file, unsigned int cmd, unsigned long arg)
{
int ret;
char which[128]="";
ret = copy_from_user(which,(void*)arg,sizeof(which));
if(ret)
{
printk("from is err \n");
return EIO;
}
printk("which=%s\n", which);
}
test.c
#include "led.h"
char buf[128] = {"lisi"};
int main(int argc, char const *argv[])
{
int fd = -1;
fd = open("/dev/myled", O_RDWR);
if (-1 == fd)
{
perror("open is error\n");
exit(1);
}
char buf[128]="i am huyue";
//image_t image = {20,1024};
//ioctl(fd, ACCESS, &image);
//ioctl(fd, ACCESS, &image);
//printf("width=%d\n",image.width);
//printf("high=%d\n",image.high);
ioctl(fd,UACCESS_BUF,buf);
typedef struct{
int width;
int high;
}image_t;
image_t image = {20,1024};
1.将结构体的数据传递到内核空间,并在内核空间进行打印
2.在内核空间,将width和 high分别+10之后的值,传递给用户空间
3.在用户空间进行打印结构体的值为{30,1034}
.h
//封装传送字符串命令码
#define UACCESS_BUF _IOW('a',1,char[128])
typedef struct{
int width;
int high;
}image_t;
//封装传送结构体表达式
#define ACCESS _IOW('a',1,image_t)
.C
long myioctl(struct file*file, unsigned int cmd, unsigned long arg)
{
int ret;
// char which[128]="";
// ret = copy_from_user(which,(void*)arg,sizeof(which));
//if(ret)
//{
//printk("from is err \n");
// return EIO;
// }
// printk("which=%s\n", which);
image_t image;
//接受用户空间传输的数据
ret = copy_from_user(&image,(void*)arg,sizeof(image_t));
if(ret)
{
printk("from is err \n");
return EIO;
}
printk("width=%d\n", image.width);
printk("high=%d\n", image.high);
image.high+=10;
image.width+=10;
//传送数据到内核空间
copy_to_user((void*)arg,&image, sizeof(image_t));
if(ret)
{
printk("to is err \n");
return EIO;
}
return 0;
}
test.c
int main(int argc, char const *argv[])
{
int fd = -1;
fd = open("/dev/myled", O_RDWR);
if (-1 == fd)
{
perror("open is error\n");
exit(1);
}
// char buf[128]="i am huyue";
image_t image = {20,1024};
ioctl(fd, ACCESS, &image);
printf("width=%d\n",image.width);
printf("high=%d\n",image.high);
}
实验现象