Search code examples
clinux-kernelkernel-moduleuserspace

How to use copy_to_user() in a kernel program?


I tried using copy_to_user() inside a loop.

for_each_process(p) {
    copy_to_user(buf, "data of p", len);
}

But, the output that I got is different. It has only the last line of data in the user space, e.g.

#Data expected to copy to user space

123 1234 12 21
1243 124 423 12
1234 422 42 423

#Current Output:
1234 422 42 423

How to copy each line to the user space from the kernel space?


Solution

  • How many times can you use copy_to_user() in a kernel program?

    As many times as you want. But they have to make sense (because anything you do in any kind of program has to make sense).

    I thought if the data that is passed into the copy_to_user() will append the data to the next line.

    No, copy_to_user does not append anything. I'm not sure where you got that idea.

    What is actually happening

    Well, you're copying the data for the first process, then overwriting it with the data for the second process, then overwriting that with the data for the third process, and so on. At the end you're left with the third process's data.

    How do transfer all three lines to the user space from the kernel space?

    Store the data for each process at a different location.