System calls
User mode and kernel mode
A bank lets customers use the counter, but only staff open the vault. The CPU works the same way. Programs run in user mode, where risky actions, like driving the disk directly, are blocked. The core of the OS, the kernel, runs in kernel mode, with full control of the machine. If a program tries a blocked action, the CPU stops it and hands control to the kernel.
System calls
A program can't open the vault, but it can ask the kernel for help with a system call. A system call is a trap: a special instruction that switches the CPU into kernel mode. The trap can only jump to fixed spots the kernel set up at boot, in the trap table. The kernel checks the request, does the work, and returns to user mode.
fork
fork makes a copy of the calling process. The caller is the parent, the new copy is the child. Both carry on from just after fork, each with its own copy of memory. In the child, fork returns 0. In the parent, it returns the child's process ID.
exec
exec loads a new program into the current process. The old code and memory are replaced, but the process ID stays the same. If it works, exec never returns, because the old code is gone. A shell runs a command by calling fork, then the child calls exec.
wait and exit
A program ends by calling exit with a status number, where 0 means success. A parent calls wait to pause until its child exits. A child that has exited but not been collected is a zombie: done, but still in the process list with its status.
Remember
- Apps run in user mode; only the kernel runs in kernel mode.
- A system call is a trap into the kernel and back.
forkcopies a process;execswaps in a new program.waitcollects an exited child; until then it is a zombie.