Processes and Threads
A process is a program in execution. It has a code section, data, heap, stack and a Process Control Block (PCB).
Process States
Process Control Block
Process ID, process state, program counter, CPU registers, scheduling info (priority), memory-management info (page tables), accounting info and I/O status.
Creating a Process: fork()
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
printf("Child: my PID is %d\n", getpid());
} else {
wait(NULL); // parent waits for child
printf("Parent: child %d finished\n", pid);
}
return 0;
}
Child: my PID is 4122
Parent: child 4122 finished
Exam pointA program calling
fork() n times (sequentially, unconditionally) produces 2ⁿ processes, so 2ⁿ − 1 are children.Process vs Thread
| Process | Thread |
|---|---|
| Independent, with its own address space | Lightweight; shares the process's code, data and files |
| Expensive context switch | Cheap context switch |
| Communicates via IPC | Communicates via shared memory |
User-level threads are managed by a library; kernel-level threads are managed by the OS. Mapping models: many-to-one, one-to-one and many-to-many.
Track your progress through the Operating System course