看内核的代码,copy_from_user/copy_to_user都是以char为单位的,如果用户空间要读写一个int型的数组到内核空间,要怎么写呢,给出示例,供大家参考。
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <linux/errno.h>
#include <linux/device.h>
#include <linux/miscdevice.h>
#include<linux/slab.h>
int test_open(struct inode *node, struct file *filp)
{
return 0;
}
int test_close(struct inode *node, struct file *filp)
{
return 0;
}
ssize_t test_read(struct file * filp, char __user * buf, size_t count,
loff_t * offset)
{
int ret;
int buffer[8] = { 88, 66, 18, 16 };
ret = copy_to_user(buf, buffer, count);
return count;
}
ssize_t test_write(struct file * filp, const char __user * buf, size_t count,
loff_t * offset)
{
int i;
int ret;
int *buffer;
buffer = kmalloc(count, GFP_KERNEL);
if (buffer == NULL) {
return -ENOMEM;
}
if (copy_from_user(buffer, buf, count)) {
ret = -EFAULT;
} else {
for (i = 0; i < count / sizeof(int); i++)
pr_info("buffer[%i]=%d\n", i, buffer[i]);
}
return count;
}
struct file_operations test_fops = {
.open = test_open,
.release = test_close,
.write = test_write,
.read = test_read,
};
static struct miscdevice test_dev = {
.minor = MISC_DYNAMIC_MINOR,
.name = "test",
.fops = &test_fops,
};
static int __init test_init(void)
{
int ret;
printk("test_init\n");
ret = misc_register(&test_dev);
if (ret != 0) {
pr_err("cannot register miscdev\n");
}
return 0;
}
static void __exit test_exit(void)
{
printk("test_exit\n");
misc_deregister(&test_dev);
}
module_init(test_init);
module_exit(test_exit);
MODULE_LICENSE("GPL v2");
应用层读写代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(void)
{
int fd;
int i;
int ret;
int length;
int buf[4] = { 16, 18, 66, 88 };
fd = open("/dev/test", O_RDWR);
if (fd < 0) {
perror("open");
return -1;
}
ret = write(fd, buf, sizeof(buf));
if (ret = !sizeof(buf)) {
printf("write err!\n");
}
ret = read(fd, buf, sizeof(buf));
if (ret != sizeof(buf)) {
printf("read err ret=%d!\n", ret);
} else {
for (i = 0; i < sizeof(buf) / sizeof(int); i++)
printf("buf[%i]=%d\n", i, buf[i]);
}
close(fd);
return 0;
}