Search code examples
processkerneldaemonspace

How does one tell whether a process is in kernel or user space?


Some processes, and in particular some daemons, can run in either kernel space or user space (sort of like how a user can run in normal or superuser mode). Is there a simple way to find out which it is for any given process (daemon)?


Solution

  • Typically (in monolithic kernels, anyway), processes can run in both user space and kernel space, depending on what they're doing. The user code will run in user space until it requires kernel services, i.e. a kernel system call. The program will then cause a trap which switches the CPU to protected mode where the kernel code executes the system call (e.g. to read or write a file). Once that is complete, the kernel switches back to user mode and the user application continues running. At all times it is the user process that's running; it's just running user code or kernel code, as appropriate.

    EDIT

    At least on Linux, I don't think there's any way to tell if a kernel-only process will ever drop to user space; the kernel is allowed to do anything it wants, after all. But, you can use some heuristics to make an educated guess. For example, pmap will tell you what user-space memory is mapped in for the process; no memory is pretty strong evidence (perhaps incontrovertible) that it's a kernel task. In the same way, if the VSZ field in 'ps l' is 0, it means the task has no user-space memory allocated. If you're just interested in whether the task is in the kernel at this moment in time, the WCHAN field in 'ps l' will give you a hint; if it's something other than -, it's in the kernel, if it's -, then it's likely in user space, but I'm not sure if it could also mean that it's just been preempted while in kernel space.