c - 为什么当我使用 copy_from_user 时,一些模糊字符添加到原始缓冲区?

标签 c linux-kernel kernel linux-device-driver kernel-module

我在内核模块中创建了 WRITE_IOCTL 并在用户模式下调用它:

ioctl(fd, WRITE_IOCTL, "Hello, Kernel!");

在内核模式下我有:

static int device_ioctl(struct file *filp,
    unsigned int cmd, unsigned long args) {
  char buff[14];

  switch (cmd) {
  case WRITE_IOCTL:
    copy_from_user( buff,(char *)args, 14);
    printk("This message received from User Space: %s\n", buff);
    break;
  }
  return 0;
}

当我运行这个 ioctl 时,我在/var/log/kern.log 中有一些类似的内容:

This message received from User Space: Hello, Kernel!vE�
This message received from User Space: Hello, Kernel!M�
This message received from User Space: Hello, Kernel!M�

如何解决这个问题?

最佳答案

可能 copy_from_user() 没有放置空字节终止符,因为 args 大于或等于您的 n 并且printk() 需要一个以 null 结尾的值,因此您正在访问垃圾值。为了解决这个问题,请将自己的 buf 初始化为零:

  char buff[14 + 1] = {0}; // +1 for make room to 0-byte-terminattor.

它将用零填充 buf 的所有字节。

编辑:

正如 @caf 在评论中提到的,您需要为空字节终止符留出一些空间。因此,不要准确地给出函数的缓冲区大小,而是将其传递为 n-1,以便函数将循环到 n,然后放入空字节。

关于c - 为什么当我使用 copy_from_user 时,一些模糊字符添加到原始缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19744964/

相关文章:

c - 整数的位反转,忽略整数大小和字节顺序

c - 警告 : incompatible implicit declaration of built-in function ‘xyz’

c - 邻居发现 C

linux-kernel - Linux 内核 - 内核中的哪些数据 block 物理写入特定磁盘分区?

linux - 从 CMA(连续内存分配器)区域迁移页面失败

c - fork() 的执行顺序?

linux - 当您调用 select(2) 时,内核如何确定套接字已准备就绪?

c - execv() 贵吗?

windows - 没有设备的设备驱动程序?

c - 安装的 VHD 上的 FSCTL_LOCK_VOLUME 失败并出现 ERROR_ACCESS_DENIED