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 fork system call

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

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

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:

#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
*/

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.

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

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

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

    printf("Hello World\n");

    return 0;
}

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

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

NextThe wait system call

Last updated 2 years ago

🍴
Fork tree visualization