These are the notes for CS Fundamentals for Placements, episode 18. In episode 17 you saw what a process is. Today you create processes yourself in C with the three system calls behind every terminal: the fork system call and its return values, the parent and child process, the process tree, the exec family (execl, execlp, execv, execvp, ...), wait and waitpid, the exit status, the zombie process, the orphan process and its adoption by init, and fork counting numericals. Every term is explained in plain words the first time it appears, and there is a full glossary at the end. All outputs below are real: the C programs were compiled with gcc -O2 (gcc 13.3) and run on Linux x86-64 on 30 October 2026, with standard output going to a pipe, exactly as in the SyntaxPilot compiler. Process ids change on every run.
A quick refresher: a process is a program in execution with its own memory and a PID (process id); every process except PID 1 has a parent, the process that created it (getppid() returns the parent's PID). A system call asks the kernel to do something (episode 15). Standard output (stdout) is where printf writes.
The six problems
| Problem | What it teaches |
|---|---|
| Start a process from a process | fork(), parent and child |
| Why did it print twice? | The stdio buffer, fflush, fork's return values, if (id == 0), wait |
| How many processes? | Fork counting, 2ⁿ, the process tree |
| Run a different program | exec, the exec family (l, v, p, e) |
| Did my child finish? | wait, waitpid, exit status, WIFEXITED, WEXITSTATUS, perror |
| Nobody waited | Zombie, orphan, adoption by init (PID 1); fork-exec-wait in a shell |
Problem 1: start a process from a process (fork)
When you type ./main, the shell (a normal process, episode 15) must start a new process for main and stay alive itself to read your next command. UNIX's answer is fork(): a system call that creates a new process by copying the process that calls it. One process goes in, two come out.
#include <stdio.h>
#include <unistd.h>
int main() {
printf("Start\n");
pid_t id = fork(); // one process goes in...
printf("Hello, fork returned %d\n", id);
return 0; // ...two come out
}
Output:
Start
Hello, fork returned 1513
Start
Hello, fork returned 0
Two surprises: Start printed twice although it comes before fork, and the two Hello lines show two different return values. (pid_t is the integer type for process ids.)
Problem 2: why did it print twice? (the buffer and fork's return values)
Surprise 1: the stdio buffer
printf does not print immediately. It writes into a buffer, a holding area in the process's own memory, and sends it out later with one write system call, because one big write is cheaper than many small ones. When stdout is a terminal, the buffer is emptied at every newline (line buffering). When stdout is a file or pipe (as in the SyntaxPilot compiler), it is emptied only when it is full or the program ends (full buffering).
Real-life example: the photocopied notebook. You write "Start" on a letter but keep it in your bag. Then everything is photocopied: notebook, bag, page number, and the unposted letter. Both copies post their letters at the end: two "Start"s. The fix: post the letter before photocopying.
| Notebook | Process |
|---|---|
| Letter written but still in the bag | "Start\n" sitting in the stdout buffer |
| Photocopy everything | fork() copies memory, variables, the buffer, the program counter |
| Both post their letters | both processes flush their buffers at exit |
| Post before copying | fflush(stdout) before fork() |
fflush(stdout) empties the buffer now. setbuf(stdout, NULL) turns buffering off completely.
Surprise 2: fork returns twice
fork() is called once but returns twice, once in each process:
| Where | fork() returns |
|---|---|
| In the parent (the original process) | the child's PID, a positive number |
| In the child (the new copy) | 0 |
| If it fails (e.g. too many processes) | -1 in the parent, and no child is created |
The child is a copy of the parent: same code, same variable values, same open files, but its own separate memory from now on (a change in one does not affect the other). Both continue from the line right after fork(). The different return values are how each one knows who it is: if (id == 0) → child code, else → parent code.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
printf("Start\n");
fflush(stdout); // empty the buffer BEFORE fork
pid_t id = fork();
if (id == 0) {
printf("child: my pid %d, parent %d\n", getpid(), getppid());
} else {
wait(NULL); // let the child finish first
printf("parent: my pid %d, child %d\n", getpid(), id);
}
return 0;
}
Output:
Start
child: my pid 1559, parent 1558
parent: my pid 1558, child 1559
Start once. The child's parent id equals the parent's own id. wait(NULL) pauses the parent until a child finishes, so the output comes in a fixed order (without it, the order of the two lines is up to the scheduler).
Problem 3: how many processes? (fork counting)
#include <stdio.h>
#include <unistd.h>
int main() {
setbuf(stdout, NULL); // no buffer: print right away
fork();
fork();
fork();
printf("hi from %d\n", getpid());
return 0;
}
Output (8 lines, 8 different PIDs, order varies):
hi from 1599
hi from 1601
hi from 1600
hi from 1604
hi from 1602
hi from 1598
hi from 1603
hi from 1605
Why 8? Every process that reaches a fork() makes one child, and both continue. Fork 1: 1 → 2. Fork 2: both fork → 4. Fork 3: all four fork → 8.
| Forks in a row | Processes | New children |
|---|---|---|
| 1 | 2 | 1 |
| 2 | 4 | 3 |
| 3 | 8 | 7 |
| n | 2ⁿ | 2ⁿ − 1 |
The process tree
Drawing parent → child links gives the process tree. For three forks (P = the original; each level is one fork):
P ─┬─ C1 ─┬─ C4 ── C7
│ └─ C5
├─ C2 ── C6
└─ C3
P makes C1, C2, C3 (at forks 1, 2, 3); C1 makes C4, C5 (forks 2, 3); C2 makes C6 (fork 3); C4 makes C7 (fork 3). On a whole system, the root of the tree is PID 1 (pstree -p shows it on Linux).
Conditions change the count
if (fork() == 0) fork();→ 3 processes: only the child forks again.if (fork() && fork()) fork();→ 4 processes (worked below in Practice).for (int i = 0; i < n; i++) fork();→ 2ⁿ.
Method: track each process separately through the code, remembering fork returns > 0 in the parent and 0 in the child, and that && / || stop early (short-circuit evaluation: in a && b, if a is 0 (false), b is never evaluated).
Problem 4: run a different program (exec)
fork gives a clone running the same program. The shell's child must run a different one (main, ls, python). The fix is exec: replace the program running in this process with another program. The kernel throws away the old text, data, heap and stack, loads the new program, and starts it from its beginning. Same process, same PID, new program, like an actor changing costume: same person, new character.
So exec never returns when it succeeds (the code that called it no longer exists). It returns -1 only if it fails.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t id = fork();
if (id == 0) { // child: become another program
char *args[] = {"echo", "I am echo now", NULL};
execvp(args[0], args);
printf("you never see this line\n");
}
int status;
waitpid(id, &status, 0); // parent waits for that child
printf("child exited with %d\n", WEXITSTATUS(status));
return 0;
}
Output:
I am echo now
child exited with 0
args is the new program's argument list (its argv): by convention args[0] is the program's own name, and the list must end with NULL.
The exec family
| Function | Arguments passed as | Finds the program | Environment |
|---|---|---|---|
execl(path, arg0, arg1, ..., NULL) |
list | full path needed | inherited |
execlp(file, arg0, ..., NULL) |
list | searches PATH | inherited |
execle(path, arg0, ..., NULL, envp) |
list | full path | e: new environment |
execv(path, argv) |
vector (array) | full path | inherited |
execvp(file, argv) |
vector | searches PATH | inherited |
execve(path, argv, envp) |
vector | full path | e: new environment |
- PATH is an environment variable listing the folders where programs live (e.g.
/usr/bin), soexeclp("echo", ...)finds/usr/bin/echo. - The environment is a list of
NAME=valuesettings a program starts with (PATH,HOME, ...). execveis the actual system call; the others are libc wrappers around it (episode 16).
Problem 5: did my child finish? (wait, waitpid, exit status)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main() {
pid_t id = fork();
if (id == 0) {
execlp("chai-maker", "chai-maker", NULL); // no such program
perror("execlp"); // only runs if exec FAILED
exit(7);
}
int status;
waitpid(id, &status, 0);
if (WIFEXITED(status))
printf("child exited with %d\n", WEXITSTATUS(status));
return 0;
}
Output (the first line goes to standard error):
execlp: No such file or directory
child exited with 7
perror("execlp")prints your text plus the message for the currenterrno(hereENOENT).exit(7)ends the process with exit status 7. The exit status is a small number (0-255) a process hands back when it ends: 0 = success, anything else = some failure, with the meaning chosen by each program (lsuses 2 for "serious trouble", as Practice 3 shows).WIFEXITED(status)is true if the child ended normally (not killed by a signal);WEXITSTATUS(status)extracts the number.WIFSIGNALED/WTERMSIGtell you if it was killed by a signal.
wait(&status) |
waitpid(pid, &status, options) |
|
|---|---|---|
| Waits for | any one child | a specific child (pid > 0), or any (pid = -1) |
| Blocks? | yes | yes, unless options = WNOHANG (just check and return) |
| Returns | the finished child's PID, or -1 if no children | the PID, 0 with WNOHANG if not finished yet, or -1 |
A shell does exactly this: in bash, echo $? prints the last command's exit status.
Problem 6: nobody waited (zombie and orphan)
The kernel must keep a finished child's exit status until the parent asks for it with wait. So what if the parent hasn't asked yet?
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
void state_of(pid_t pid) { // ask the kernel: what state is it in?
char path[64], line[128];
sprintf(path, "/proc/%d/status", pid);
FILE *f = fopen(path, "r");
if (!f) { printf("child %d: gone\n", pid); return; }
while (fgets(line, sizeof line, f))
if (!strncmp(line, "State", 5)) printf("child %d %s", pid, line);
fclose(f);
}
int main() {
pid_t id = fork();
if (id == 0) return 0; // child finishes at once
sleep(1); // parent busy, no wait() yet
state_of(id);
wait(NULL); // collect the exit status
state_of(id);
return 0;
}
Output:
child 1685 State: Z (zombie)
child 1685: gone
A zombie process (defunct process) has finished, but its parent has not yet collected its exit status. It uses no memory or CPU; it keeps only its PID, exit status and an entry in the process table (the kernel's list of all processes). Many zombies can use up all PIDs, so long-running parents must wait (or handle the SIGCHLD signal, which the kernel sends a parent when a child ends, episode 19). After wait, the entry is removed: reaping.
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t id = fork();
if (id > 0) {
printf("parent %d: bye!\n", getpid());
fflush(stdout);
usleep(200000); // 0.2 s, then the parent ends
return 0;
}
printf("child: my parent is %d\n", getppid());
fflush(stdout);
sleep(1); // by now the parent is gone
printf("child: my parent is %d\n", getppid());
return 0;
}
Output:
parent 2084: bye!
child: my parent is 2084
child: my parent is 1
An orphan process is a child still running after its parent ended. The kernel gives it a new parent, PID 1 (init): adoption by init. init calls wait for its adopted children, so they never stay zombies. (On some Linux systems a process can register as a "subreaper" and adopt orphans instead of PID 1.)
| Zombie | Orphan | |
|---|---|---|
| Child | finished | still running |
| Parent | alive, hasn't called wait |
already finished |
| Holds | PID + exit status + a process-table slot | everything a normal process has |
| Harmful? | many zombies exhaust PIDs | harmless |
| Resolved by | the parent calling wait, or the parent ending (then init reaps it) |
init adopts it and later reaps it |
ps shows |
Z / <defunct> |
normal state, PPID = 1 |
How a shell runs ./main: fork, exec, wait
- The shell reads
./main. fork()→ a clone of the shell (child getsid == 0).- In the child,
exec("./main")→ the clone becomesmain, keeping its PID. - The shell calls
wait/waitpid, collects the exit status (no zombie), and shows the prompt again.
(Commands ending in & run in the background: the shell skips step 4 for them and reaps them later.)
Common mistakes (and the real output)
| Mistake | Real output | Why | Fix |
|---|---|---|---|
printf("Start\n"); fork(); with stdout going to a pipe or file |
Start printed twice |
the unflushed buffer is copied into the child | fflush(stdout) before fork() |
No error handling after exec |
the child carries on running the parent's code | exec returns only on failure | perror(...) then exit(...) right after exec |
execlp("chai-maker", ...) with a missing program |
execlp: No such file or directory |
not found on PATH | check the name / path; handle the failure |
| A long-running parent that never waits | State: Z (zombie) |
the exit status is never collected | wait / waitpid, or handle SIGCHLD |
Forgetting NULL at the end of exec's arguments |
undefined behaviour (garbage arguments or a crash) | exec can't find the end of the list | always end the list/array with NULL |
| Assuming the parent always prints first | output order changes between runs | the scheduler decides who runs first | use wait to order output |
Counting fork(); fork(); as 3 processes |
4 lines printed | each fork doubles all existing processes | n forks in a row → 2ⁿ |
Mini project: a tiny shell
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
char line[256];
while (printf("mysh> "), fflush(stdout), fgets(line, sizeof line, stdin)) {
char *args[16];
int n = 0;
for (char *w = strtok(line, " \n"); w && n < 15; w = strtok(NULL, " \n"))
args[n++] = w;
args[n] = NULL;
if (n == 0) continue;
if (strcmp(args[0], "exit") == 0) break;
pid_t id = fork();
if (id == 0) {
execvp(args[0], args);
perror(args[0]);
exit(127);
}
int status;
waitpid(id, &status, 0);
printf("[exit %d]\n", WEXITSTATUS(status));
}
return 0;
}
Compile it on Linux and type commands like echo hello, ls, ls /nope, nosuchcmd, exit. Each line is split into words with strtok, then fork → exec → wait, exactly like a real shell. Extensions: add cd (it must be a built-in: why? because a child's chdir can't change the parent's folder), and & for background jobs.
Practice
1. How many times does this print? for (int i = 0; i < 4; i++) fork(); printf("hi\n");
Solution
2⁴ = 16. Real run (with setbuf(stdout, NULL)): 16 lines of hi.
2. How many processes does if (fork() && fork()) fork(); create in total?
Solution
Track each process:
- Fork A. The child of A gets 0, so
&&stops: it skips everything. (1 process) - The parent gets > 0, so it evaluates fork B. The child of B gets 0: the condition is false, it skips the body. (1 process)
- The parent gets > 0 from B too, so the condition is true: it calls fork C, making one more child.
Total: original + child A + child B + child C = 4 processes. Real run:
hi from 2521
hi from 2522
hi from 2523
hi from 2520
3. Run ls with execvp on a missing folder and print its exit status.
Solution
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t id = fork();
if (id == 0) {
char *args[] = {"ls", "/no-such-folder", NULL};
execvp(args[0], args);
perror("execvp");
exit(127);
}
int status;
waitpid(id, &status, 0);
printf("ls exited with %d\n", WEXITSTATUS(status));
return 0;
}
Output:
ls: cannot access '/no-such-folder': No such file or directory
ls exited with 2
ls itself ran (exec succeeded) and reported failure with status 2.
4. Make a zombie that lasts 5 seconds, then reap it.
Solution
In the zombie demo, change sleep(1) to sleep(5). During those 5 seconds, ps -o pid,stat,comm in another terminal shows the child with Z (<defunct>). After wait(NULL), it disappears.
5. What does each process print? int x = 5; if (fork() == 0) x++; else x--; printf("%d\n", x);
Solution
The child prints 6, the parent prints 4. After fork each has its own copy of x, so changes don't affect the other.
6. A child calls exec successfully. Does its PID change? Does its parent change?
Solution
Neither. exec replaces the program, not the process: same PID, same parent, same open files (unless marked close-on-exec).
Quick quiz
int main() {
setbuf(stdout, NULL);
fork();
fork();
printf("hi\n");
}
How many times does hi print? A. 2 B. 3 C. 4 D. 8
Answer
C. 4. Two forks in a row: 1 → 2 → 4 processes, each prints once: 2² = 4.
Interview questions
- What does
fork()return? The child's PID in the parent, 0 in the child, -1 on failure. - What does the child inherit from the parent? A copy of memory (code, data, heap, stack), open file descriptors, environment, current directory. It gets a new PID and its own copy of everything from then on.
- Why does output sometimes print twice after fork? The stdio buffer was not flushed before fork, so both processes hold the same pending text and both flush it.
- fork vs exec? fork creates a new process (a copy); exec replaces the program inside the current process (same PID). Together: fork then exec in the child.
- Why doesn't exec return on success? The calling program's code has been replaced; there is nothing to return to.
- Name the exec variants and what l, v, p, e mean.
execl,execlp,execle,execv,execvp,execve; l = list, v = vector, p = search PATH, e = pass environment.execveis the system call. - wait vs waitpid? wait: any child, blocks. waitpid: a specific child, can be non-blocking with WNOHANG.
- What is a zombie process? How do you prevent it? A finished child whose exit status hasn't been collected. Prevent with wait/waitpid, a SIGCHLD handler, or by letting init adopt it.
- What is an orphan process? A running child whose parent has ended; it is adopted by init (PID 1), which reaps it.
- How many processes do n forks in a row create? 2ⁿ in total, 2ⁿ − 1 new.
- How does a shell run a command? fork → exec in the child → wait in the parent → print the prompt.
- Why must
cdbe a shell built-in? Each process has its own current directory; a child's change can't affect the parent shell.
Glossary
| Term | Meaning in plain words | Example |
|---|---|---|
fork() |
System call that creates a new process by copying the caller | pid_t id = fork(); |
| Parent process | The process that called fork | gets the child's PID |
| Child process | The new copy created by fork | gets 0 |
| Fork return value | > 0 in the parent (child's PID), 0 in the child, -1 on failure | if (id == 0) |
pid_t |
Integer type for process ids | pid_t id |
| Buffer | A holding area where output waits before being written | the stdout buffer |
| Line buffering | Buffer emptied at each newline (terminals) | typing in a terminal |
| Full buffering | Buffer emptied only when full or at exit (files, pipes) | the compiler's output |
fflush(stdout) |
Empty the stdout buffer now | before fork |
setbuf(stdout, NULL) |
Turn stdout buffering off | fork counting demo |
| Process tree | The parent → child links of all processes | pstree |
| Short-circuit evaluation | &&/\|\| stop as soon as the answer is known |
fork() && fork() |
| exec | Replace the program in this process with another | execvp("echo", args) |
| Exec family | execl, execlp, execle, execv, execvp, execve |
l, v, p, e |
| Argument vector (argv) | The NULL-terminated list of a program's arguments | {"echo", "hi", NULL} |
| PATH | Environment variable listing folders to search for programs | /usr/bin |
| Environment | NAME=value settings a program starts with |
HOME=/home/you |
wait() |
Block until any child ends; collect its status | wait(NULL) |
waitpid() |
Wait for a specific child, optionally without blocking | waitpid(id, &s, 0) |
WNOHANG |
waitpid option: check and return immediately | polling a child |
| Exit status | Number a process returns when it ends; 0 = success | exit(7) |
WIFEXITED / WEXITSTATUS |
Did it exit normally? / its exit number | 7 |
perror |
Print a message plus the text for errno |
execlp: No such file or directory |
| Standard error (stderr) | Separate output stream for error messages | where perror writes |
| Zombie process | Finished child whose exit status isn't collected yet | State: Z (zombie) |
| Process table | The kernel's list of all processes | one slot per PID |
| Reaping | Collecting a child's exit status so its entry is removed | wait() |
SIGCHLD |
Signal sent to a parent when a child ends | used to reap children |
| Orphan process | A running child whose parent has ended | parent id becomes 1 |
| Adoption by init | The kernel makes PID 1 the orphan's new parent | getppid() → 1 |
| init (PID 1) | The first user process; reaps orphans | systemd |
| Shell | Command interpreter: reads, forks, execs, waits | bash |
| Built-in command | A command the shell runs itself, without fork/exec | cd, exit |
Summary
fork()copies the calling process and returns twice: the child's PID to the parent, 0 to the child, -1 on failure. Both continue after the fork.- Output printed before fork can appear twice when stdout is a pipe/file: flush with
fflush(stdout)first. - n forks in a row create 2ⁿ processes; conditions and short-circuiting change the count; parent → child links form the process tree.
execreplaces the program in the current process (same PID) and never returns on success. Letters: l = list, v = vector, p = PATH, e = environment;execveis the system call.wait/waitpidblock until a child ends and give its exit status (WIFEXITED,WEXITSTATUS).- A finished but un-waited child is a zombie; a child whose parent ended is an orphan, adopted and reaped by init (PID 1).
- Every shell runs commands with fork → exec → wait.
Next episode: inter-process communication: shared memory, message passing, pipes, FIFOs, message queues, signals, sockets and RPC.