typestar

fork in C

fork returns twice: zero in the child, the child's pid in the parent.

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    pid_t pid = fork();

    if (pid < 0) {
        perror("fork");
        return 1;
    }
    if (pid == 0) {
        printf("child %d\n", (int) getpid());
        return 7;
    }

    int status = 0;
    waitpid(pid, &status, 0);
    if (WIFEXITED(status)) {
        printf("child exited with %d\n", WEXITSTATUS(status));
    }
    return 0;
}

How it works

  1. Both processes continue from the same line.
  2. The parent must wait, or it leaves a zombie.
  3. A return of -1 means the fork failed.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
345
Tokens
108
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 62 seconds.

Type this snippet

Step 1 of 4 in Processes & signals, step 7 of 14 in Systems programming.

← Previous Next →