---
description: In this section we shall see how the fork() system call works
---

# 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="https://1063801461-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuJPHFv2wuD88XZAJjg6z%2Fuploads%2F8X3VRZwPpDcrxqS79xre%2Ffork.png?alt=media&#x26;token=00226bcc-63a3-418e-8654-d7291c303308" alt=""><figcaption><p><strong>Fork tree visualization</strong></p></figcaption></figure>
