Sub topic 1
Kernel Mode, User Mode, and Interrupts
Prerequisites
This chapter assumes you can write basic C (functions, pointers, headers), that you know the CPU, registers, memory, and interrupts from computer organization, and that you understand simple queues.
Kernel Mode and User Mode
A CPU runs in one of two privilege levels. In user mode, a program can access only its own memory and a restricted set of instructions. In kernel mode, the operating system kernel can access all hardware and all memory. The CPU hardware enforces this split, so a faulty user program cannot overwrite the kernel or another program's memory.
System Calls
A system call is a controlled request from a user program to the kernel, such as reading a file or creating a process. The program places the call number and arguments in registers and executes a trap instruction. The CPU switches to kernel mode, the kernel checks the arguments and does the work, and then the CPU returns to user mode with the result in a register.
C programs rarely issue traps directly. Library wrappers such as write and fork do this for you.
Interrupts
An interrupt is a signal from hardware, such as a keyboard or disk controller, that makes the CPU pause and run a kernel handler. A timer interrupt lets the kernel regain control of the CPU, which is the basis for preemptive scheduling.
What a Process Is
A process is a running program together with its state: its memory, open files, and registers. Its memory has four regions: text (code), data (globals), heap (dynamic allocation, growing upward), and stack (function calls, growing downward).
Process States and the PCB
A process moves among the states new, ready, running, waiting, and terminated. The kernel stores each process's details in a Process Control Block (PCB), which holds the process ID, state, program counter, saved registers, memory information, and open file list.
Creating Processes with fork, exec, and wait
fork creates a child process that copies the parent. It returns 0 in the child and the child's PID in the parent. exec replaces the child's program image with a new program. waitpid lets the parent collect the child's exit status.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t pid = fork();
if (pid == 0) {
execlp("echo", "echo", "hello from child", (char *)NULL);
_exit(127);
}
int status;
waitpid(pid, &status, 0);
printf("child finished\n");
return 0;
}Context Switching and Its Cost
A context switch saves the state of the running process to its PCB and loads the saved state of another process. The switch takes CPU time that does no useful work, and the new process often finds its cache cold. Frequent switches therefore reduce throughput.
Exercise
In the program above, execlp fails and the child reaches _exit(127). What does the parent print?
Show answer
The child exits with status 127 and prints nothing. The parent's waitpid returns, and the parent prints "child finished".