UNIX processes using C/C++
  • 🍴The fork system call
  • ⌚The wait system call
  • 🆔Process ID
  • 🔌Signals in UNIX
    • 🗄️Signal Handlers
  • 🥃Executing system commands
  • 📁Sharing information between processes
    • 🕚Bidirectional pipe
  • 🖥️Applications
    • 💻Console Application 1
    • 💻Console Application 2
  • ⚽Named pipe FIFO
Powered by GitBook
On this page

The wait system call

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

Observe the code below carefully and predict the output

#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;
}

Outputs

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

1 2 3 4 5 6 7 8 9 10
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

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

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

// Output
// 1 2 3 4 5 6 7 8 9 10
PreviousThe fork system callNextProcess ID

Last updated 2 years ago

⌚