What is the kernel?
- C course
- Expert
- Lesson 1/47
- 5 min
Learn the kernel concept and user/kernel mode.
What is the kernel?
The kernel is the heart of the operating system; it manages hardware and serves processes. C programs run in user mode and cannot touch hardware directly.
When needed they switch to kernel mode. The switch happens via a system call (syscall). The kernel validates the request and, if safe, performs it. This separation keeps a buggy program from crashing the whole system. The POSIX kernel interface is declared in <unistd.h>.
Mode switch and trap
The switch from user mode to kernel mode happens through a trap instruction. When a process invokes syscall, the CPU raises its privilege level and jumps into kernel code.
After the kernel finishes, control returns to the same instruction. The switch is costly; user-space libraries such as libc cache or batch calls. On modern x86 CPUs the SYSCALL and SYSRET instructions speed up this transition. C programmers usually call wrappers like read and write; direct syscall is rarely needed.
Practice Print kernel modes
Define an enum cpu_mode with USER_MODE = 0, KERNEL_MODE = 1. Use printf to print each mode on its own line as "USER_MODE=0" and "KERNEL_MODE=1".
Starter code
#include <stdio.h>
// Define the cpu_mode enum
// Print each mode as NAME=value
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
enum cpu_mode { USER_MODE = 0, KERNEL_MODE = 1 };
int main(void) {
printf("USER_MODE=%d\n", USER_MODE);
printf("KERNEL_MODE=%d\n", KERNEL_MODE);
return 0;
}Expected output
USER_MODE=0 KERNEL_MODE=1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In which mode can hardware be accessed directly?
- Kernel mode Correct answer
- User mode
- Fault mode
- Idle mode
Explanation: Kernel mode can run hardware instructions directly.
2 Complete the cpu_mode enum
enum cpu_mode { ____ = 1 };
enum cpu_mode { KERNEL_MODE = 1 };
Explanation: KERNEL_MODE names the privileged mode.
3 Match kernel concepts
| Term | Meaning |
|---|---|
user_mode |
Application mode |
kernel_mode |
Kernel mode |
trap |
Mode switch instruction |
syscall |
Kernel service request |