Processes โ Easy Exam Guide Unit u04 (Processes, exec, signals, pipes). Every idea in simple words, linked to how the exam asks it. This is the biggest topic โ it gives 4 question types. ๐ด = comes a lot.
Written in simple (B1) English. Read it from top to bottom before the exam.
0How "processes" come in the exam
Processes is the biggest topic on the exam. It gives you four kinds of questions, and together they are worth a lot of points (about 9โ11 points in every paper). The good news: each kind follows clear rules. Learn the rules here, then practise.
| The question you will see | How often | Section |
|---|---|---|
๐ด A C program with fork/exec/system โ "what is the output?" or "how many times does X print?" | almost every exam (the headline skill) | ยง2 + ยง3 |
| ๐ด True/false about the PCB, zombie, orphan, process states, the exec family | almost every exam | ยง1, ยง3, ยง4 |
| ๐ด True/false about signals (kill, handlers, SIGCHLD, race conditions) | most exams | ยง5 |
| ๐ด True/false about pipes (and sometimes a write-code pipe task) | most exams | ยง6 |
1What a process is, and the PCB ๐ด comes a lot
Program vs process
- A program is a file on the disk. It does nothing by itself โ it is passive.
- A process is a program that is running โ it is active. One program can run as many processes at the same time.
Each process has its own memory: code (the instructions), data (global variables), heap (memory you ask for at run time, grows up), and stack (function calls and local variables, grows down). It also has CPU registers (like the program counter).
The Process Control Block (PCB)
The kernel keeps one PCB for each process. The PCB holds everything the system needs to know about that process:
- the process state (see below) and the PID (process number);
- the program counter and a copy of all CPU registers;
- memory information (limits, base);
- the list of open files;
- scheduling information (priority, queues);
- the signal table (which handler for which signal).
On a context switch (when the CPU changes from one process to another), the kernel saves the old process into its PCB and loads the new process from its PCB. A context switch is only overhead โ no useful work happens during it.
Process states
| State | Meaning |
|---|---|
| New | just created |
| Ready | can run, but waiting for a free CPU |
| Running | using the CPU now |
| Waiting | blocked, waiting for an event or I/O |
| Terminated | finished, resources released |
A running process does not go straight back to Running. It goes Running โ Ready (the scheduler stops it), and then Ready โ Running later. Only one process per CPU is Running.
- "When a process dies, its PCB is freed immediately." No โ a zombie keeps its PCB until the parent waits.
- "Context switching means deleting the PCB of the old process." No โ it only saves and loads.
2fork() and how to read these programs ๐ด the headline skill โ almost every exam
The most common process question gives you a C program with fork, exec, and system, and asks for the output, or "how many times does X print?". You do not guess โ you follow a method. This section gives you that method.
What fork() does
fork()makes a copy of the current process. Now there are two processes: the parent and the new child. The child copies the code and a copy of the data, and gets its own PID.- fork is called one time but returns two times โ once in each process:
- in the parent, it returns the child's PID (a number > 0);
- in the child, it returns 0;
- on error, it returns โ1 (no child is made).
- So
if (fork() > 0) { ... } else { ... }means: the first block is the parent, the second is the child. - After fork, both processes run the same code from that point. They run independently.
The method to trace the output
- Find what each process prints at the start. If a
printfis before the fork, every fresh start prints it once. - Follow the branches. After each
fork(), draw the parent path and the child path. Count how many processes you have. - Watch
setbuf(stdout,0). This makes output unbuffered. Then output comes out at once and is not duplicated by fork. (If the output is buffered, fork copies the buffer, so text can print twice โ a classic trap.) - exec replaces the program (see ยง3). After a successful
execlp(...), the lines after it do not run. The process starts the program again from the beginning (a "fresh start"). - system("...") runs a new program and waits for it to finish. So a
system("./pgrm n-1")is also a "fresh start". - For "how many times" questions, use a count rule. Write
S(n)= how many fresh starts happen for inputn. Each start makes more starts, so you build a small formula.
printf("%d ", getpid()); // every start prints its PID once
n = atoi(argv[1]);
if (n <= 0) return 1; // n=0 prints and stops
if (fork() == 0) { // the CHILD...
execlp(argv[0], argv[0], "n-1", NULL); // re-starts ./pgrm n-1
}
system("./pgrm n-1"); // the PARENT also starts ./pgrm n-1
So each start makes two new starts (one by the child's exec, one by the parent's system). Count the starts by level for ./pgrm 3:
S(3) = 1 S(2) = 2 (two starts at level 2) S(1) = 4 S(0) = 8 (these just print and stop) Total = 1 + 2 + 4 + 8 = 15 PIDsAnswer: 15. You did not guess โ you counted.
setbuf(stdout,0) and remember exec does not come back.- Thinking the lines after a successful
execstill run. They do not. - Forgetting that
system()waits for its command (it does not run in parallel with the parent's next line). - Forgetting buffering: with no
setbuf, fork can duplicate buffered text.
3The exec family and system() ๐ด comes a lot
What exec does
execreplaces the program of the current process with a new program. It does not make a new process โ the PID stays the same.- The new program starts from its
main(). exec returns nothing on success โ the old code is gone. It returns โ1 only on error. So code after a good exec never runs. - Open files stay open after exec. So shell redirections (
>,<) still work in the new program. - The normal way to run a program is fork + exec + wait: the parent forks, the child execs the new program, the parent waits for it.
The six versions โ the letters l / v / p / e
| Letter | Meaning |
|---|---|
| l (list) | you give the arguments one by one in the call, and end with NULL |
| v (vector) | you give the arguments as an array argv[] that ends with NULL (use this when you do not know the number of args at compile time) |
| p (path) | the system searches the program name in the PATH folders, so you can pass just the name |
| e (environment) | you give your own environment array envp[] |
The first argument is the program name (it becomes argv[0]). The real arguments come after it.
execlp("cp", "cp", "f1", "f2", NULL); // OK: 'p' searches PATH, arg0 = "cp"
execl ("/bin/cp", "cp", "f1", "f2", NULL); // OK: full path given
execl ("cp", "f1", "f2", NULL); // WRONG: 'l' with no 'p' needs a full path
execlp("ls", "-l", NULL); // WRONG: missing arg0 (should be "ls","ls","-l",NULL)
system()
system("command") is the easy way: inside, it does fork + exec (of a shell) + wait. It runs the command string and comes back when the command is finished.
- "You should check exec's return value to see if it worked, by the code after it." No โ after success there is no code; exec returns only on error.
- "
execl(\"cp\", ...)works." No โ withoutpyou need a full path. - "exec is built using
system()." No โ it is the other way around (systemuses fork + exec).
4wait, exit, zombie & orphan ๐ด comes a lot
exit()ends a process and frees most of its resources.wait()/waitpid()let the parent collect the child's exit status. This is called "reaping" the child.waitblocks until a child ends.
| Zombie ๐ง | Orphan ๐ถ | |
|---|---|---|
| What happened | the child finished, but the parent did not call wait yet | the parent died first, while the child is still running |
| PCB | the child's PCB still exists (it keeps the exit status) | the child is alive, so it has a normal PCB |
| Can it run code? | No โ a zombie is already dead | Yes โ it keeps running normally |
| Who fixes it | the parent calls wait โ the PCB is freed | init (PID 1) adopts it; its PPID becomes 1 |
| End | stays a zombie until the parent waits | when it dies, init reaps it โ it never stays a zombie |
- "A zombie can still run code." No โ it is dead.
- "The zombie itself must call wait." No โ the parent calls wait.
- "When adopted, the orphan gets a new PID." No โ only its parent (PPID) changes, not its PID.
5Signals ๐ด most exams
A signal is a "software interrupt" โ a short, async message sent to a process to tell it that something happened. A signal carries no data, only its type.
Common signals
| Signal | Meaning |
|---|---|
| SIGKILL, SIGSTOP | cannot be caught, ignored, or blocked โ so the system always keeps control |
| SIGCHLD | sent to the parent when a child stops or ends (default: ignore) |
| SIGINT / SIGTSTP | Ctrl-C / Ctrl-Z |
| SIGUSR1 / SIGUSR2 | free for your own use |
| SIGALRM | sent by alarm() after some seconds |
| SIGPIPE | sent when you write to a pipe with no reader |
What a process can do with a signal
Three choices: default action, ignore it (SIG_IGN), or catch it with a handler function.
signal(sig, handler)sets a handler. Note:signal()does not send a signal โ it only chooses what to do. It returns the old handler, orSIG_ERRon error.signal(SIGCHLD, SIG_IGN)stops children from becoming zombies (the kernel auto-reaps them). After this, a laterwait()returns โ1 (there is no child to wait for). Note:SIG_DFLis not enough for this, even though SIGCHLD's default is "ignore".
Sending signals and waiting
kill(pid, sig)is the system call that sends a signal. The shellkillcommand does the same thing (e.g.kill -9sends SIGKILL). A user can signal only their own processes; the superuser can signal any.kill(pid, 0)sends nothing โ it just tests if the process exists.raise(sig)sends a signal to itself (=kill(getpid(), sig)).pause()waits for any signal.alarm(n)sends SIGALRM afternseconds.sleepcan be woken early by a signal.
Problems with signals (the exam likes these)
- Signals are not queued. If the same signal comes twice quickly, one can be lost. The order of different signals is not sure.
- A handler must use only reentrant (safe) functions.
printfandmallocare not safe inside a handler. - Race condition: if you do
alarm(n); pause();and the signal arrives beforepause()runs, the signal is lost andpause()waits forever.
signal(SIGCHLD,SIG_IGN) auto-reaps children (so no zombies, and wait then returns โ1); sleep can be interrupted; handlers must be reentrant; handlers can cause race conditions; both shell kill and the syscall kill() can end a process.- "With
signal()you can ignore any signal." No โ SIGKILL and SIGSTOP cannot be ignored. - "
raise()sends a signal to another process." No โ it sends to itself. - "Getting a signal always ends the process." No โ it depends on the signal and the handler.
6Pipes and IPC ๐ด most exams
Processes can talk in two ways: shared memory (good for big data) or messages (good for small data). The pipe is the oldest message channel. It lives in memory, so it is faster than a file.
How a pipe works
pipe(fd)makes a pipe with two ends:fd[0]= read end,fd[1]= write end. You write tofd[1]and read fromfd[0].- A pipe is half-duplex: data goes one way at a time.
- You must call
pipe()beforefork(), so the child inherits the two ends. Each side then closes the end it does not use. - You read and write a pipe with the same
readandwritecalls as a file. You can send a whole struct in onewriteโ you do not need to send byte by byte.
Blocking, EOF, and SIGPIPE (the key rules)
| Action | What happens |
|---|---|
read on an empty pipe | blocks (waits) until data comes |
read when all write ends are closed | returns 0 = EOF (not an error, not SIGPIPE) |
write on a full pipe | blocks until there is space (it does not return an error) |
write when all read ends are closed | the kernel sends SIGPIPE |
write of โค PIPE_BUF bytes | is atomic (PIPE_BUF is 4096 on Linux) |
Common bug and tips
- Classic bug: if you forget to
closethe unused write end, the reader never sees EOF, so itsreadwaits forever and the program hangs. - One writer + one reader is the normal case. Many readers/writers is allowed but the result is mixed and not sure.
- To send strings of different lengths, send the length first, then the bytes (a "length prefix"), or use an end marker.
- The shell pipe
|connects the stdout of one command to the stdin of the next.
- "A read on a pipe is always blocking." No โ if all writers are closed it returns EOF.
- "A write on a full pipe returns an error." No โ it blocks.
- "PIPE_BUF is the maximum size of the pipe." No โ it is the atomic-write limit.
- "A read with no writers causes SIGPIPE." No โ that gives EOF; SIGPIPE is for write with no readers.
- "You can write on both ends at the same time." No โ a pipe is one direction.
7One-page trap sheet
PCB / states
- PCB holds: state, PID, program counter, all registers, open files, scheduling info, signal table.
- Context switch = save old PCB + load new PCB (not delete). A zombie still has a PCB.
fork / exec / system (output tracing)
- fork: called once, returns twice โ parent gets child PID (>0), child gets 0, error โ1.
setbuf(stdout,0)= unbuffered (no duplicated text). Without it, fork can double buffered output.- exec replaces the program, same PID, returns only on error; code after a good exec never runs.
- system() = fork + exec + wait; it waits for the command. Count "fresh starts" with a small formula.
- exec letters: l = list of args + NULL ยท v = argv array + NULL ยท p = search PATH ยท e = own environment.
- Without
pyou must give a full path. arg0 is the program name (argv[0]).
zombie / orphan
- Zombie = child finished, parent did not wait. Keeps PCB, cannot run code; the parent reaps it.
- Orphan = parent died first. Still runs; init (PID 1) adopts it; PPID changes (not PID); init reaps it.
signals
- SIGKILL and SIGSTOP cannot be caught/ignored/blocked.
signal()only chooses, it does not send. signal(SIGCHLD,SIG_IGN)= no zombies; then wait returns โ1.raise= signal to self.- Signals are not queued (can be lost). Handlers must be reentrant (no printf/malloc). Beware alarm+pause races.
pipes
- fd[0] = read, fd[1] = write. Make the pipe before fork; close the unused end (or the reader hangs).
- read empty โ blocks; read with no writers โ EOF (0). write full โ blocks; write with no readers โ SIGPIPE.
- Atomic up to PIPE_BUF (4096). PIPE_BUF โ pipe size. One writer + one reader is the safe case.