Fork System Call | Operating System EP-08

Fork System Call | Operating System EP-08

In this article, I am going to explain about fork system call. We will see some examples of the implementation of the fork system call to get a better understanding of the concept.

Fork

  • The fork is a system call.

  • It comes under process control system call.

  • We use a fork system call to make child process.

  • Suppose, we have a C program, if we write fork() in it then a child process will be created. This child process also has its unique ID.

  • We use the concept of fork because let’s assume that the parent process is busy, so a clone will be created which will perform the task which parent process is unable to complete/execute. (Another approach to solving this problem and is known as Thread it is somewhat different from the fork.)

  • Fork system call generally returns two values 0 and +1 (+ve). 0 denotes child process while +ve denotes parent process. -1 can also be created this happens when due to some reasons child process cannot be created, for example in case the operating system/kernel is busy.

  • Let us take an example to understand about fork system call.

    main() {
     fork();
     printf("Hello");
    }
    

rCaPmE8tm.png

  • In this case, two processes are running parallel, due to the fork statement.

  • Here Hello will be printed two times because, before the execution of the printf statement, the fork statement will be executed and a child process is created.

  • The id of the child process is 0, while the id of the parent process is +1 (+ve)

    • Let’s see one more example; this will help you to understand the concept of fork system call more clearly.

      main() {
       fork();
       fork();
       printf("Hello");
      }
      

IDn3vER8j.png

  • In this case, at the time of 2nd fork C1 and P will behave as a parent. Therefore the following output will be obtained as shown in the diagram. Here Hello will be printed 4 times.
  • Total number of execution = 2^n
  • Total number of child process = 2^n-1
  • n stands for number of fork commands.