CodeBlanks Logo Icon CodeBlanks

fork

Learn to create processes with fork.

What is fork?

fork creates an exact copy of the running process. The original is the parent, the new copy is the child. Both run the same code but are different processes.

fork returns a pid_t value: 0 to the child, the child's ID (positive) to the parent, -1 on error. You check the return value to know which process you are in. This is the foundation of concurrent programming.

Parent and child

After fork, parent and child continue from the same point. Use if (pid == 0) for the child branch and else for the parent branch.

The child copies the parent's file descriptors and memory but does not share memory. Descriptors point to the same table; both see the same files. When the child finishes, the parent must wait for it; otherwise the child becomes a zombie. You will see wait in the next lesson.

Practice Create a process with fork

Create a process with pid_t pid = fork();. In the if (pid == 0) branch, have the child exit with _exit(0). In the parent branch, print with printf("fork done\n");.

Starter code

main.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

// Call fork
// Exit in child
// Print in parent

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(void) {
    pid_t pid = fork();
    if (pid == 0) {
        _exit(0);
    }
    printf("fork done\n");
    return 0;
}

Expected output

fork done

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does fork return to the child process?

  • -1
  • The parent's PID
  • 0 Correct answer
  • 1

Explanation: The child gets 0; the parent gets the child's PID.

2 fork call

Question
pid_t pid = ____();
Answer
pid_t pid = fork();

Explanation: fork creates parent and child processes.

3 Match process functions

Term Meaning
fork Creates process
exec Replaces program
wait Waits for child
getpid Returns PID

All lessons in Advanced