/* fork() makes a copy of this process. The copy is called the child.
   Both carry on from the same line, and fork() tells them apart:
   it returns 0 in the child and the child's process ID in the parent.
   Build it and run it:
     cc -o fork fork.c
     ./fork
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    printf("parent: about to fork\n");
    fflush(stdout); /* empty the output buffer, or the child would print it again */

    pid_t pid = fork();
    if (pid < 0) {
        perror("fork");
        return 1;
    }
    if (pid == 0) {
        printf("child: I'm the copy, and fork() gave me 0\n");
        return 3; /* the child's exit code */
    }

    int status;
    waitpid(pid, &status, 0); /* wait for the child to finish */
    printf("parent: fork() gave me the child's PID, and the child exited with code %d\n", WEXITSTATUS(status));
    return 0;
}
