A program calls fork() three times in a row and then executes printf("hello\n"). How many processes exist at the end, how many are new, and how many times is hello printed?
A process is a program in execution, tracked by the OS through its PCB, its state and its queues; threads are lighter units of execution inside a process. Process creation (fork/exec/wait), IPC and threading models are exam favourites.
A program is a passive entity: an executable file such as /bin/ls or a.out lying on disk. A process is that program in execution — an active entity with a program counter (PC) that points at the next instruction, a set of CPU registers, and memory of its own. Two users running the same editor are two separate processes that happen to share the same program text.
When the OS loads a program it builds an address space with a standard set of regions. Picture memory from the lowest address (top row) to the highest (bottom row):
| Region | What it holds | Size / growth | Example in C |
|---|---|---|---|
| Text (code) | The machine instructions; usually read-only and shareable between processes | Fixed | the compiled body of main() |
| Data | Global and static variables that have an initial value | Fixed | int limit = 100; at file scope |
| BSS | Global and static variables without an initial value (zero-filled at load time) | Fixed | static int table[100]; |
| Heap | Memory allocated while the program runs | Grows upward, toward the stack | p = malloc(64); |
| Stack | Activation records: parameters, return addresses, local variables | Grows downward, toward the heap | int i; inside a function |
#include <stdio.h>
#include <stdlib.h>
int limit = 100; /* data section: initialised global */
int hits; /* BSS: uninitialised global */
int main(void) /* the instructions live in text */
{
int local = 5; /* stack: local variable */
int *buf = malloc(10 * sizeof(int)); /* buf on stack, 40 bytes on heap */
hits = local + limit;
printf("%d\n", hits);
free(buf);
return 0;
}malloc() → heap; local variables, parameters and return addresses → stack; initialised globals → data; the code → text. The free gap between heap and stack lets both grow; if they collide the process runs out of memory (a stack overflow or a failed malloc).A process also owns resources that are not memory: open files, sockets, signal handlers, a current working directory, and user and group IDs. Together with the CPU registers these make up the process context — everything the OS must preserve to stop the process and later resume it as if nothing had happened.
As it runs, a process changes state. The standard five-state model (Galvin/Silberschatz) has: New (being created), Ready (in memory and waiting only for the CPU), Running (instructions executing — at most one process per CPU core), Waiting or Blocked (waiting for an event such as I/O completion or a signal) and Terminated (finished; resources being reclaimed).
| Transition | Triggered by |
|---|---|
| New → Ready | Admit: the OS accepts the job and gives it memory (long-term scheduler) |
| Ready → Running | Dispatch: the CPU scheduler selects it |
| Running → Ready | Preemption: a timer interrupt ends its time slice, or a higher-priority process arrives |
| Running → Waiting | It requests I/O, calls wait() for a child, or waits for a lock or event |
| Waiting → Ready | The awaited event happens (for example the disk's I/O-completion interrupt) |
| Running → Terminated | It calls exit(), returns from main, or is killed |
The seven-state model (Stallings). When memory is short, the OS may suspend a process by swapping it out to disk. Two states are added: Ready/Suspend (on disk, but would be ready if brought into memory) and Blocked/Suspend (on disk and still waiting for its event). Typical extra transitions: Blocked → Blocked/Suspend (swap out), Blocked/Suspend → Ready/Suspend (the event occurs while the process is on disk), Ready/Suspend → Ready (activate, i.e. swap in) and Ready → Ready/Suspend (swap out to free memory). The medium-term scheduler makes the swap-out and swap-in decisions; Blocked/Suspend → Ready/Suspend is triggered by the awaited event itself.
Linux shows a process's state in the STAT column of ps: R running or runnable, S interruptible sleep (waiting), D uninterruptible sleep (usually disk I/O), T stopped, Z zombie. Note that Linux lumps ready and running together as R.
The OS represents each process by a Process Control Block (PCB), also called a task control block. It is the process's identity card and its saved CPU snapshot in one structure; all PCBs together form the process table. In Linux the PCB is the C structure task_struct, and every task is linked into a doubly linked list.
PCBs are threaded onto queues. The job queue holds every process in the system; the ready queue (usually a linked list of PCBs) holds those in memory and waiting for the CPU; each I/O device has a device queue of processes waiting for it. A process migrates between these queues all its life — Galvin draws this as the queueing diagram.
| Scheduler | Also called | Decides | Runs | Effect |
|---|---|---|---|---|
| Long-term | Job scheduler | Which jobs from the disk pool are loaded into memory | Infrequently (seconds to minutes) | Controls the degree of multiprogramming (number of processes in memory) |
| Short-term | CPU scheduler | Which ready process gets the CPU next | Very often (every few milliseconds) | Must be very fast; its decisions are the CPU-scheduling algorithms |
| Medium-term | Swapper | Which process to swap out to disk and later swap back in | When memory is overcommitted | Reduces the degree of multiprogramming; improves the process mix |
A good long-term scheduler admits a balanced mix of I/O-bound processes (short CPU bursts, lots of I/O) and CPU-bound processes (long computations). If all are I/O-bound the ready queue is nearly always empty; if all are CPU-bound the devices sit idle. Time-sharing systems such as UNIX and Windows often have no real long-term scheduler — every new process simply enters the ready queue.
The dispatcher is the module that hands the CPU to the process chosen by the short-term scheduler: it switches context, switches to user mode and jumps to the proper location in the user program. The time it takes to stop one process and start another is the dispatch latency.
A context switch saves the state of the running process into its PCB and loads the saved state of the next process from its PCB. It is pure overhead — the system does no useful work for any user while switching. Its cost depends on memory speed, the number of registers to copy and hardware support: some processors keep several register sets, so a switch only changes a pointer. On modern hardware the switch itself takes microseconds, but there is a hidden cost: caches and the TLB go cold, so the next process runs slowly for a while.
The step-through diagram on this page follows one complete switch from process P0 to P1 and back again.
In UNIX and Linux a process creates a child with the fork() system call. The child is an almost exact copy of the parent: same program, copies of the data, heap and stack, the same open files — but a new PID. Modern kernels use copy-on-write: parent and child share the same physical pages until one of them writes, so fork() is cheap. Processes therefore form a tree rooted at init/systemd (PID 1); the command pstree draws it.
fork() — returns 0 in the child, the child's PID in the parent, and −1 if no child could be created. Both processes continue with the instruction after the call.exec() family (execl, execlp, execv, execvp, execve) — replaces the caller's memory image with a new program. The PID stays the same, and on success exec never returns.wait(&status) / waitpid() — the parent blocks until a child terminates, collects its exit status and lets the kernel release the child's PCB.exit(status) — ends the calling process; the status value is delivered to the parent's wait().#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid = fork();
if (pid < 0) { /* fork failed */
perror("fork");
exit(1);
} else if (pid == 0) { /* child */
execlp("ls", "ls", "-l", (char *)NULL);
perror("exec"); /* only if exec fails */
exit(1);
} else { /* parent */
int status;
wait(&status);
printf("child %d finished, status %d\n", (int)pid, WEXITSTATUS(status));
}
return 0;
}| Zombie (defunct) process | Orphan process | |
|---|---|---|
| What happened | The child terminated, but the parent has not yet called wait() | The parent terminated while the child is still running |
| What remains | Only its process-table entry (PID and exit status) | A live, running process |
| Who cleans up | The parent's wait(); if the parent dies, PID 1 adopts and reaps the zombie | init/systemd (PID 1) adopts it and reaps it when it ends |
How ps shows it | State Z, marked <defunct> | Its parent PID (PPID) becomes 1 (or a designated subreaper) |
| Risk | Many zombies exhaust PIDs and process-table slots | Usually harmless — daemons are orphaned deliberately |
Some systems practise cascading termination: when a parent exits, the OS kills all of its descendants. UNIX does not; it re-parents orphans to PID 1 instead. A zombie cannot be removed with kill -9 — it is already dead; only a wait() by its parent (or the parent's own death) clears it.
Processes are either independent (they cannot affect or be affected by others) or cooperating (they share data). Reasons to cooperate are information sharing, computation speed-up on multiple cores, modularity and convenience. Cooperating processes need interprocess communication, which comes in two fundamental models.
shmget/shmat, or POSIX shm_open + mmap)send(P, msg) and receive(Q, msg) through the kernelIn direct communication each process names its partner explicitly (send(P, m)), and a link joins exactly one pair. In indirect communication messages go to a mailbox (port) that several processes may share. A blocking send is called synchronous; if both send and receive block, the exchange is a rendezvous. Buffering may be zero capacity (the sender always waits for the receiver), bounded or unbounded.
pipe(fd) returns fd[0] for reading and fd[1] for writing. It is one-directional and usable only between related processes, typically parent and child. The shell's ls | wc -l is a pipe.mkfifo; it has a name in the file system, so unrelated processes can use it, and it survives after they exit. On UNIX it is half-duplex.msgget/msgsnd/msgrcv, or POSIX mq_open).| Signal | Number (Linux x86) | Meaning and default action |
|---|---|---|
| SIGHUP | 1 | Terminal hang-up; daemons often re-read their configuration |
| SIGINT | 2 | Interrupt from the keyboard (Ctrl+C); terminate |
| SIGKILL | 9 | Kill at once — cannot be caught, blocked or ignored |
| SIGSEGV | 11 | Invalid memory reference; terminate with a core dump |
| SIGTERM | 15 | Polite request to terminate; the default of the kill command |
| SIGCHLD | 17 | A child stopped or terminated; the parent may now call wait() |
| SIGSTOP | 19 | Stop (pause) the process — cannot be caught or ignored |
kill PID sends SIGTERM (15) by default; kill -9 PID sends SIGKILL. Pipes connect related processes; FIFOs (named pipes) also connect unrelated ones.clone()), Windows threads| Model | Mapping | Parallelism | Blocking system call | Examples |
|---|---|---|---|---|
| Many-to-one | Many user threads → one kernel thread | None: one thread in the kernel at a time | Blocks the whole process | Solaris Green Threads, GNU Portable Threads |
| One-to-one | Each user thread → its own kernel thread | Full | Blocks only that thread | Linux, Windows (cost: a kernel thread per user thread) |
| Many-to-many | Many user threads multiplexed on a smaller or equal number of kernel threads | Yes | The kernel runs another thread | Solaris before version 9, Windows ThreadFiber |
| Two-level | Many-to-many, plus the option to bind a user thread to one kernel thread | Yes | As many-to-many | IRIX, HP-UX, Tru64 UNIX |
Pthreads is the POSIX standard thread API (IEEE 1003.1c) — a specification that Linux, macOS and other UNIX systems implement. The core calls: pthread_create() starts a thread running a given function, pthread_join() waits for it to finish, pthread_exit() ends the calling thread, and pthread_mutex_lock()/pthread_mutex_unlock() guard shared data. Compile with gcc prog.c -pthread. Java (Thread, Runnable) and Windows (CreateThread) offer equivalent APIs.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
long sum = 0; /* shared by all threads (data section) */
void *runner(void *param) /* the new thread starts here */
{
int upper = atoi(param);
for (int i = 1; i <= upper; i++)
sum += i;
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t tid; /* thread identifier */
if (argc != 2) {
fprintf(stderr, "usage: %s <n>\n", argv[0]);
return 1;
}
pthread_create(&tid, NULL, runner, argv[1]);
pthread_join(tid, NULL); /* wait for the worker to finish */
printf("sum = %ld\n", sum);
return 0;
}Two more exam terms: a thread pool creates a fixed number of threads at start-up and hands them tasks, which is faster than creating a thread per request and caps resource use; thread cancellation is either asynchronous (the target is terminated immediately) or deferred (the target checks periodically and exits cleanly at a cancellation point).
Try the problem first, then reveal the working one step at a time.
A program calls fork() three times in a row and then executes printf("hello\n"). How many processes exist at the end, how many are new, and how many times is hello printed?
How many processes, including the original, exist after one execution of fork() && fork() || fork();?
75% of an application can be split across threads; the rest is serial. What speed-up do 2 cores and 4 cores give, and what is the upper limit?
A process is created, waits in the ready queue, runs for 3 ms, issues a disk read, receives its data, runs until its time slice expires, is dispatched again and calls exit(). List its states and the event behind each transition.
How many child processes does for (i = 0; i < 4; i++) fork(); create? How many times does a printf placed after the loop execute?
A global int x = 10; exists. After pid = fork(); the child executes x = x + 5; printf("child: %d\n", x); while the parent executes wait(NULL); x = x - 5; printf("parent: %d\n", x);. What is printed, and in which order?
In the five-state model, is each transition possible? Give a reason. (a) Ready → Waiting (b) Waiting → Running (c) Running → Ready (d) New → Running
A server forks a child for every request but never calls wait(). What accumulates, how does it appear in ps, and what are three ways to fix it?
40% of a program is inherently serial. What speed-up can 8 cores give, and what is the maximum possible speed-up?
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.