Creating message character device - /dev/msg

In this post, let's create a simple character device - /dev/msg, which will store a user message.

Theory

We use copy_to_user and copy_from_user to copy data to/fro in between user space and kernel space.

unsigned long copy_to_user ( void __user *  to, const void *  from, unsigned long  n); -- Copies data from kernel space to user space.

unsigned long copy_from_user (void *to, const void __user *from,unsigned long n); -- Copies data from user space to kernel space.

Both on success returns 0 else returns number of bytes not copied.

Why copy_to_user and copy_from_user is needed instead of memcpy?


  • It verifies that the memory passed is in a region of memory that the process have access to and the address is not pointing to kernel space by using access_ok macro
  • User pages being addressed might not be currently present in memory, if the kernel directly tries to access the pages which are not in memory, it will result in page fault and kernel will panic on page fault. But if there is page fault during copy_from_user kernel does not panic, but returns -EFAULT.
  • It also handles if it encounters an invalid address during copy.

Code:



Sample Test Application:




Output:

$ ./testapp 
write : 12
Read:hello world
Read:



Comments

Popular posts from this blog

bb.utils.contains yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig

PR, PN and PV Variable in Yocto