0

I'm currently working with a custom device driver that I installed. I'm very new to this and having trouble understanding how to get the data that I write into it from the command line.

For example, I write data to the file like so:

echo -n "test" > /dev/custom

And then I merely want to get the string here, so I can use the characters within:

static ssize_t custom_write (struct file *f, const char *buf, size_t len, loff_t *offset)
{
  printk(KERN_ALERT "Test\n");
    return len;
}
2
  • Isn't the string in buf? Commented Nov 13, 2020 at 22:09
  • That's my first thought, but I'm unsure how to access it properly. Most times I've tried I've received some sort of permission error. Commented Nov 13, 2020 at 22:10

1 Answer 1

1

The string is in buf, but it's in user memory. You need to use copy_from_user() to copy to kernel memory.

static ssize_t custom_write (struct file *f, const char *buf, size_t len, loff_t *offset)
{
    char custom_buffer[MAX_BUFFER_SIZE];
    size_t custom_buffer_size = len;
    if (custom_buffer_size > MAX_BUFFER_SIZE) {
        custom_buffer_size = MAX_BUFFER_SIZE;
    }
    if (copy_from_user(custom_buffer, buf, custom_buffer_size) != 0) {
        return -EFAULT;
    }
    printk(KERN_ALERT "Test %.*s\n", (int)custom_buffer_size, custom_buffer);
    return custom_buffer_size;
}
Sign up to request clarification or add additional context in comments.

1 Comment

For printk(KERN_ALERT "Test %s\n", custom_buffer); the string in custom_buffer[] is not properly null terminated. printk(KERN_ALERT, "Test %.*s\n", (int)custom_buffer_size, custom_buffer); would be better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.