简体   繁体   中英

Passing enum from kernel module to UserSpace program

I have to keep a track of KeyStates, I want to use the following enum,

typedef enum{
KeyOn,
KeyOff,
}State; 

I want to pass this to the userspace program. I am not sure how my copy_to_user() function should be written. How do i pass the state of the key press to the userspace?

Let's first address the issue of what copy_to_user does and why is it needed?

Modern computers work with a mechanism that's called Virtual Memory . This is a mechanism that allows 2 main things - The separation of memory between different processes, and the allocation of more virtual memory than there is physical memory on the machine.

For each process, there's aa distinct virtual memory space, and different processes could have the same Virtual Address point to different Physical addresses.

The kernel maps between the Virtual address spaces of processes to their Physical addresses. But what happens when you pass the Kernel a pointer?

The pointer you pass to the kernel is a virtual address in the user space processes virtual memory. The kernel needs to translate that address into the corresponding physical address in order to fill that address with the result. For that operation copy_to_user was created - It takes a pointer in the Kernel's address space and copies it into a pointer in the user processes address space.

From all written above you should already understand that your question is invalid - an Enum value is not a pointer, so there's no need to call copy_to_user on it, you can just return it as is.

The next thing we need to discuss is what's an ENUM. An enum is a syntactic sugar provided by many modern languages to allow the definition of values as human-readable identifiers. The enum keys don't exist past-compilation, there's just integer values passed between functions. They are translated much like #define into their value, and the named key doesn't matter anymore.

The only thing you need to do when returning an ENUM from the kernel, is make sure you #include the proper header in the user program so that you can translate the numbers which the enum keys represent correctly in your program. In runtime - numbers are all that's being passed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM