Skip to content
AgileLogics
5 min read

Process Management: fork and exec

Prerequisites: Multithreading with pthreads

fork() (POSIX systems — Linux and macOS, not native Windows) creates a near-exact copy of the current process — both the original (parent) and the copy (child) keep running from the same point, distinguished only by fork's return value.

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

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

    if (pid == 0) {
        printf("Child process\n");
    } else {
        printf("Parent process, child PID: %d\n", pid);
        wait(NULL); // wait for the child to finish
    }
    return 0;
}

exec (execvp and friends) replaces the current process's program entirely with a different one — combined with fork, this is how a shell runs another program: fork a child, then have that child exec the requested command.