student@ubuntu:~$
c 5/5 50 XP

Processes

0%

Quick Reference

fork and exec pattern:

pid_t pid = fork();
if (pid == -1) {
    perror("fork");
    _exit(1);
} else if (pid == 0) {
    // Child: replace with new program
    execl("/bin/ls", "ls", "-la", NULL);
    perror("execl");   // Only reached if exec fails
    _exit(1);
} else {
    // Parent: wait for child
    int status;
    waitpid(pid, &status, 0);
    if (WIFEXITED(status))
        printf("Child exited with %d\n", WEXITSTATUS(status));
}

Key functions:

Function Purpose
fork() Create child process
execl/execv/execlp Replace current program
wait() Wait for any child
waitpid() Wait for specific child
getpid() Get current PID
getppid() Get parent’s PID

Common Pitfalls

  • Fork bomb – An infinite loop of fork calls creates processes exponentially. Never run this.
  • Missing error check – fork() returns -1 on failure. Always check.
  • Code after exec – Only runs if exec fails. Always follow exec with perror and _exit.
  • Missing wait – Creates zombie processes. Always wait for your children.

Unlocks

Complete this skill to see what it unlocks.