驱动 (3.2) copy_to_user

copy_to_user

/*驱动端*/
/********filename : test.c********************************/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/init.h>
#include <asm/uaccess.h>

#define MISC_NAME "test"
#define BOADRID_READ  9999

long misc_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
	unsigned int __user *argp = (unsigned int __user *)arg;	

	unsigned int boardid = 90;
	int ret =1;

	switch(cmd)
	{
	case  BOADRID_READ:

		ret = copy_to_user(argp,&boardid, sizeof(unsigned int));
		//ret = copy_to_user(&arg,&boardid, sizeof(unsigned int));
		if(ret)
		{
			printk("ret : %d\n",ret);
			printk("IOC_VDEC_GET_VIDEO_LOSS error\n");
			return -1;
		}

		break;

	default:
		return -1;
	}
	return 0;
}

int misc_close(struct inode * inode, struct file * file)
{
	return 0;
}


/**********************************************************/
static int misc_open(struct inode *inode, struct file *file)
{
    printk("misc open\n");
    return 0;
}

/**********************************************************/

static const struct file_operations misc_fops =
{
    .owner   =   	THIS_MODULE,
    .open    =   	misc_open,
	.unlocked_ioctl = misc_ioctl,
	.release        = misc_close
};

/**********************************************************/

static struct miscdevice misc_dev =
{
    .minor = MISC_DYNAMIC_MINOR,//这是次设备号,如果为255,会自动分配一个次设备号.MISC_DYNAMIC_MINOR就是255
    .name = MISC_NAME,//设备的名字,加载成功会在/dev/下创建一个以MISC_NAME为名字的设备
    .fops = &misc_fops,//文件操作指针,供上层调用
};

/**********************************************************/

static int __init misc_init(void)
{
    int ret;
    ret = misc_register(&misc_dev);
    if (ret)
    {
        printk("misc_register error\n");
        return ret;
    }

    return 0;
}

static void __exit misc_exit(void)
{
    misc_deregister(&misc_dev);
}

/**********************************************************/

module_init(misc_init);
module_exit(misc_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("XXX");


/*APP端*/
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


#define BOADRID_READ  9999

int main(int argc, const char *argv[])
{

	int fd;
	int ret;
	int id;
	char * file = "/dev/test";
	fd = open(file, O_RDWR);
	if (fd < 0)
	{
		printf("open %s failed!\n", file);
		return -1;
	}
	ret = ioctl(fd,BOADRID_READ,&id);
	if(ret < 0){
		printf("get board id failed!!!\n");
	}else{
		printf("get board id sueecssed!!!\n");
	}
		printf("%d\n",id);

	return 0;
}

Makefile

ifneq  ($(KERNELRELEASE),)
obj-m:=test.o
else
KDIR := /lib/modules/$(shell uname -r)/build
PWD:=$(shell pwd)
all:
    make -C $(KDIR) M=$(PWD) modules
clean:
    rm -f *.ko *.o *.symvers *.cmd *.cmd.o
endif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值