C

Notes about the C programming language.

Forking processes

You can create a new process by calling the fork function.

The new process (the child) is a copy of the original process (the parent). Both processes continue running from the same point.

#include <stdio.h>
#include <unistd.h>

int main()
{
    printf("This will print once\n");
    fork();
    printf("This will print twice\n");
    return 0;
}

This function is called once but returns twice.1

In each process, fork returns a different result: the parent receives the process id of the child, and the child receives 0.

#include <stdio.h>
#include <unistd.h>

int main()
{
    pid_t pid = fork();
    if (pid == 0) {
        printf("I am the child\n");
    } else {
        printf("I am the parent\n");
    }
    return 0;
}

Learning

  1. Advanced Programming in the UNIX Environment, Third Edition (W. Richard Stevens)