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

# The wait system call

Observe the code below carefully and predict the output

{% code fullWidth="false" %}
```c
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[]){
    int id = fork();
    int n = (id == 0) ? 1 : 6;
    
    for (int i = 0; i < 5; i++)
        printf("%d ", i + n);
    
    return 0;
}
```
{% endcode %}

## Outputs

As it turns out, we get different outputs each time. Example:

{% code overflow="wrap" fullWidth="false" %}
```
1 2 3 4 5 6 7 8 9 10
```
{% endcode %}

```
6 7 8 9 10 1 2 3 4 5
```

```
6 7 8 9 10
```

The last output occurs when the main thread gets terminated before the child process. In order to prevent this and always get the first output, we need to stop the execution of the main thread till the child process is running.

This is where the wait() system call comes in

<pre class="language-c" data-full-width="false"><code class="lang-c">#include &#x3C;stdio.h>
#include &#x3C;unistd.h>

int main(int argc, char *argv[]){
    int id = fork();
    int n = (id == 0) ? 1 : 6;
    
<strong>    if(id != 0) wait();
</strong>    
    for (int i = 0; i &#x3C; 5; i++)
        printf("%d ", i + n);
    
    return 0;
}

// Output
// 1 2 3 4 5 6 7 8 9 10
</code></pre>
