Skip to main content

Processes and Threads

Process​

A process is a program in execution: code, data, heap, stack and OS bookkeeping stored in a process control block (PCB) (PID, state, registers, memory maps, open files).

Process states​

New -> Ready -> Running -> Terminated
^ |
| v
+----- Waiting (I/O or event)

A context switch saves the state of the running process into its PCB and loads another one. It is pure overhead, so schedulers try not to switch too often.

Creating processes (POSIX)​

fork.c
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
pid_t pid = fork(); // duplicates the calling process
if (pid == 0) {
printf("child\n");
} else {
wait(NULL); // parent waits for the child
printf("parent\n");
}
return 0;
}

fork() returns 0 in the child and the child's PID in the parent. exec() replaces the current program image.

Threads​

A thread is a unit of execution inside a process. Threads of one process share code, heap and open files, but each has its own stack and registers.

ProcessThread
MemoryOwn address spaceShared with siblings
Creation costHighLow
CommunicationIPC (pipes, sockets, shared memory)Shared variables
FailureIsolatedOne bad thread can corrupt the process

Inter-process communication (IPC)​

  • Pipes and named pipes (FIFOs)
  • Message queues
  • Shared memory (fastest, needs synchronisation)
  • Sockets (also across machines)
  • Signals (simple notifications)
TIP

Interview question: "What is a zombie process?" A child that has terminated but whose parent has not yet called wait(), so its PCB entry remains in the process table.