Copy_to_user问题

时间:2013-01-30 20:10:44

标签: device-driver kernel-module

我为设备编写了模块,我的阅读功能出现了问题:

ssize_t my_sys_read(struct file *f, char __user *buffer, size_t s, loff_t *off){

    char * myBuffer = "ossec buffer";
    size_t read_bytes;

    if (s > ( sizeof(char) * 13 ) ) s = ( sizeof(char) * 13 );

    if (!access_ok(%VERIFY_WRITE, (void *) buffer, s)) return -EFAULT;
        read_bytes = copy_to_user((void *) buffer, (void *) myBuffer, s);

    printk(KERN_INFO "myBuffer %s", myBuffer);
    printk(KERN_INFO "buffer %s", buffer);

    read_bytes = s - ( sizeof(char) * 13 );

    return read_bytes;

}

我真的不知道为什么但副本不能正常工作,打印的缓冲区对我来说毫无意义。

 [10038.885838] buffer \xffffff81\xffffffc3\xffffffcb\x1a

我想问题出现在副本中,因为使用该设备的程序很简单。

int main(void)
  {
    int fd = open(device_name, O_RDONLY);
    if(fd < 0)
    {
      printf("Error: Impossible to open device, action not permited.\n");
      return 0;
    }

    char * buff;
    int read_bytes;
    read_bytes = read(fd, buff, (13 * sizeof(char) ) );

    printf(" %s\n", buff);


  }

谢谢!

1 个答案:

答案 0 :(得分:1)

char * buff;
int read_bytes;
read_bytes = read(fd, buff, (13 * sizeof(char) ) );

你正在使用指针buff而不为它分配内存,它是一个带有随机值的悬空指针。你需要做

char *buff = new char();

  char buff;
  int read_bytes;
  read_bytes = read(fd, &buff, (13 * sizeof(char)) );