Time sharing problems: performance and control
The OS must have control over the CPU when processes run. If programs run directly on CPU, the OS would be “just a library”.
If a process wants to do some restricted operations (e.g. disk IO, or get more resource), use protected control transfer (user mode and kernel mode).
Applications run on user mode(用户态), and OS runs on kernel mode(内核态).
Allow the kernel to expose some interfaces, such as:
Those operations are actually done by the OS.
User mode and kernel mode are actually hardware level (CPU) modes. Kermel use trap to enter kernel mode, and use return-from-trap to return to user mode.
When a program need to perform restricted operations, OS switches to kernel mode, finish that and return to user mode.
Switching between modes is at a cost: performance loss.
Processes periodically give up CPU by making system calls such as yield(). If a process never makes system calls, OS can’t gain control of CPU.
OS starts a timer on booting. Every some milliseconds the timer raises an interrupt. Then the process is forced to halt, state is saved, and an interrupt handler is called.