https://offlinemark.com/2021/05/12/an-obscure-quirk-of-proc/

https://devconnected.com/understanding-processes-on-linux/


TL;DR:

In summary, **fork()** creates a new process by duplicating the calling process, and returns the child process ID to the parent process and 0 to the child process. The parent and child processes then continue to execute the same program, starting from the instruction immediately following the **fork()** call, but with their own separate memory space.

**fork()** is a system call in the C library (POSIX) that creates a new process by duplicating the calling process. It creates an exact copy of the calling process, including the program counter, register values, and memory contents.

When a program calls **fork()**, the operating system creates a new process, called the child process, which is an exact copy of the calling process, called the parent process. The child process is given a new process ID, but both the parent and child process continue to execute the same program, starting from the instruction immediately following the **fork()** call.

The **fork()** system call returns a value to the calling process. In the parent process, it returns the process ID of the child process. In the child process, it returns 0. This allows the parent and child processes to distinguish themselves and take different actions.

When the child process is created, it has its own copy of the parent’s memory. This is known as copy-on-write. So when child process modifies any memory, it creates a new copy of the memory page, this way it does not affect the parent process.

Here is an example of a C program that creates a new process and establishes a pipe for inter-process communication (IPC) to share memory:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
 
int main()
{
    int pipefd[2]; // pipe file descriptor
    char buffer[100];
    pid_t pid;
    int status;
 
    // create a pipe
    if (pipe(pipefd) == -1) {
        perror("pipe failed");
        exit(EXIT_FAILURE);
    }
 
    // fork a new process
    pid = fork();
    if (pid < 0) {
        perror("fork failed");
        exit(EXIT_FAILURE);
    }
 
    if (pid > 0) { // parent process
 
        close(pipefd[0]); // close the read end
        write(pipefd[1], "Hello from parent", 17); // write to the pipe
        wait(&status); // wait for child to finish
 
    } else { // child process
 
        close(pipefd[1]); // close the write end
        read(pipefd[0], buffer, sizeof(buffer)); // read from the pipe
        printf("Child received: %s\n", buffer);
 
    }
 
    return 0;
}

🌱 Back to Garden