← All lessons
How processes and threads work
Run a command: fork, then exec
Shell
Kernel
Child
shell.c
char *line = readline("$ "); // the shell reads what you typedchar *argv[] = { line, NULL }; pid_t pid = fork();if (pid == 0) { // only the child takes this branch execvp(argv[0], argv); // replaces this program, never returns _exit(127); // only reached if exec failed}int status;waitpid(pid, &status, 0); // the parent sleeps until 413 exitsprintf("%d\n", WEXITSTATUS(status));program.c
// the program you namedint main(int argc, char **argv) { list(argc > 1 ? argv[1] : "."); return 0; // returning from main calls exit(0)}fork() in a loop doubles the processes every pass
Process tree pstree
processes
children made
hi printed
PIDs here follow the order of each pass. On a real machine the scheduler decides who forks first
loop.c
int n = N;for (int i = 0; i < n; i++) fork(); // every process alive runs fork() hereprintf("hi\n"); // runs once in every processTopics
Next: How virtual memory works
Open lesson