> For the complete documentation index, see [llms.txt](https://octave-1.gitbook.io/c-unix/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://octave-1.gitbook.io/c-unix/the-fork-system-call.md).

# The fork system call

{% hint style="info" %}
All the content written here and in the following sections are meant for Linux/UNIX based systems only. The terms ***thread*** and ***program*** are used interchangeably as we're not concerned about their differences for the time being
{% endhint %}

The fork() function creates a new process that runs parallel to the main thread. The new process can execute the same code as the main thread or some other code based on certain criteria that is specified in the code itself.

Example:

{% code fullWidth="false" %}

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

int main(int argc, char *argv[]){
    int id = fork();
    char *pr = (id == 0) ? "child" : "parent";
    printf("Hello World from %s process\n", pr);
    return 0;
}

/*Output
Hello World from parent process
Hello World from child process
*/
```

{% endcode %}

Notice: The parent process is being executed before the child process in this case. The fork() method returns an integer which is the process id (PID) of the child process and is always 0 in case of a child process.

## Visualizing the fork tree

Observe the following code snippets and predict many times will ***Hello World*** be printed.

{% code fullWidth="false" %}

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

int main(int argc, char *argv[]){

    fork();
    fork();
    fork();

    printf("Hello World\n");

    return 0;
}
```

{% endcode %}

Answer: 2³ = 8. Since the fork() function is called 3 times.

Explanation: The following diagram shows how the fork() system calls get executed

<figure><img src="/files/mLgTSDy9kS0VH7DDuJbD" alt=""><figcaption><p><strong>Fork tree visualization</strong></p></figcaption></figure>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://octave-1.gitbook.io/c-unix/the-fork-system-call.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
