作业要求:
typedef struct{
int width;
int high;
}image_t;
用户空间: width = 10 high = 200
将用户空间数据传递给内核空间,在内核空间进行打印,打印之后需要每个变量+10,在传递给用户空间,在用户空间打印增加后的值
作业实现过程:
头文件:
#ifndef __MYLED_H__
#define __MYLED_H__
#define UACCESS_BUF _IOW('a',1,char [128])
#define UACCESS_STRUCT _IOWR('b',0,image_t)
#endif
源文件:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include "myled.h"
#define CNAME "myled"
int major;
typedef struct{
int width;
int high;
}image_t;
int myled_open(struct inode *inode, struct file *file)
{
printk("%s:%s:%d\n",__FILE__,__func__,__LINE__);
return 0;
}
ssize_t myled_read (struct file *file, char __user *ubuf, size_t size, loff_t *loff)
{
return size; //5.返回拷贝数据大小
}
ssize_t myled_write(struct file *file, const char __user *ubuf, size_t size, loff_t *loff)
{
return size; //5.返回拷贝数据大小
}
long myled_ioctl (struct file *file, unsigned int cmd, unsigned long args)
{
int ret;
image_t image;
ret=copy_from_user(&image,(void*)args,sizeof(image));
if(ret)
{
printk("copy from user is error\n");
return -EIO;
}
printk("width:%d\n",image.width);
printk("high:%d\n",image.high);
image.high+=10;
image.width+=10;
ret=copy_to_user((void*)args,&image,sizeof(image));
if(ret)
{
printk("copy from user is error\n");
return -EIO;
}
return 0;
}
int myled_close (struct inode *inode, struct file *file)
{
printk("%s:%s:%d\n",__FILE__,__func__,__LINE__);
return 0;
}
const struct file_operations fops = {
.open = myled_open,
.read = myled_read,
.write = myled_write,
.unlocked_ioctl = myled_ioctl,
.release = myled_close,
};
static int __init mycdev_init(void)
{
//1.注册字符设备驱动
major = register_chrdev(0,CNAME,&fops);
if(major < 0) //2.判断返回值
{
printk("register chrdev is error\n");
}
//3.打印主设备号
printk("register chrdev major=%d\n",major);
return 0;
}
static void __exit mycdev_exit(void)
{
//1.注销字符设备驱动
unregister_chrdev(major,CNAME);
}
module_init(mycdev_init);
module_exit(mycdev_exit);
MODULE_LICENSE("GPL");
测试文件:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/ioctl.h>
#include "myled.h"
typedef struct{
int width;
int high;
}image_t;
int main(int argc,const char * argv[])
{
image_t image={
.high=10,
.width=10,
};
int fd = -1;
fd = open("/dev/myled",O_RDWR);
if(fd == -1)
{
perror("open is error\n");
return -1;
}
ioctl(fd,UACCESS_STRUCT,&image);
printf("high=%d,width=%d",image.high,image.width);
close(fd);
return 0;
}