来自char设备模块

时间:2017-03-21 13:14:51

标签: arrays string linux-kernel output echo

我正在尝试在Linux驱动程序中实现char设备驱动程序。当我尝试将字符串回显到我的驱动程序中时,结果非常奇怪。

我存储我输入的字符串的代码:

int max_size = 1;
char store[1] = {0};
char message[100] = {0};
ssize_t hello_write(struct *filep, const char *buffer, size_t length, loff_t *position)

{
  if(length> max_size)
     length = max_size;
  if(copy_from_user(message, buffer, length))
     return -EFAULT;
  strncpy(store, message, max_size);
  printk(KERN_INFO "Actually stored in kernel:%s", store);
  return max_size;
}
ssize_t hello_read(struct file *filep, char *buffer, size_t length, loff_t *postion)
{
  int error_count = 0;
  error_count = copy_to_user(buffer, store, max_size);
  if(error==0){
    printk(KERN_INFO "read message from kernel: %s", store);
    return 0;
  }
  else{
    printk(KERN_INFO "failed to send %d chars to user", error_count);
    return -EFAULT;
  }
}

测试:

echo ginger > /dev/test
cat /dev/test

我打算只存储每个输入字符串的第一个字母,任何具有函数strncpy的东西?

store the string one by one

1 个答案:

答案 0 :(得分:2)

write系统调用返回的值被解释为处理的字节数

与其他标准输出实用程序echo一样,重复调用write() syscall ,直到它处理所有输入字节

因此,当您只想存储输入的单个字节时,需要返回输入的全长以将其标记为已处理。

.write的更正确实施将是:

ssize_t hello_write(struct *filep, const char * __user buffer, size_t length, loff_t *position)
{
  if((*position == 0) && (length > 0)) {
    // Store the first byte of the first input string.
    if(copy_from_user(message, buffer, 1))
       return -EFAULT;
    strncpy(store, message, 1);
  }
  printk(KERN_INFO "Actually stored in kernel:%s", store);
  // But mark the whole string as processed
  *position += length;
  return length;
}