Linux读写int型数组demo

看内核的代码,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;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值