【问题标题】:copy_to_user to pass datatype of int - objectcopy_to_user 传递 int 的数据类型 - 对象
【发布时间】:2021-03-27 10:49:40
【问题描述】:

我有一个int 变量,我正在尝试使用copy_to_user(buf,intflag_obj,sizeof(int)),但它给了我段错误。如何解决这个问题

更新

    static ssize_t mychardev_read(struct file *file, char __user *buf, size_t count, loff_t *offset)
    {
        int flag=10;
        wait_event_interruptible(wq, flag != 0);
        int *data =flag;
        size_t datalen = strlen(data);
        flag=0;

        printk("Reading device: %d\n", MINOR(file->f_path.dentry->d_inode->i_rdev));

        if (count > datalen) {
            count = datalen;
        }

        if (copy_to_user(buf,&data, count)) {
            return -EFAULT;
        }

        return count;
    }

【问题讨论】:

  • 很高兴知道如何将指针传递给内核以及如何使用它。顺便说一句,当您说段错误时,您的意思是哎呀?
  • flag+"hello" 是什么?
  • @OznOg 标志 int
  • 我的意思是flag+"hello" 是一个指向无处的指针,当标志超过 5 时......似乎是错误的
  • @666:“我正在尝试将单词 hello 与全局标志值连接起来” - 表达式 flag+"hello" 绝对是这样做的错误方式。有关连接 int 和 string 的正确方法,请参阅 that question

标签: linux linux-kernel linux-device-driver


【解决方案1】:

由于您想将flag 的值与单词“hello”连接起来,我猜您希望将flag 的值作为字符串读取。

您可以使用char [] 变量和snprintf 函数来构造要读取的值:

    char data[11 + sizeof("hello")];
    size_t datalen;

    snprintf(data, sizeof(data), "%dhello", flag);
    datalen = strlen(data);

    if (count > datalen) {
        count = datalen;
    }

    if (copy_to_user(buf, data, count)) {
        return -EFAULT;
    }

    return count;

【讨论】:

    猜你喜欢
    • 2015-06-06
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 2014-03-07
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    相关资源
    最近更新 更多