Calculation in parent and child process using fork() in C++

C++Server Side ProgrammingProgramming

In this section we will see how to use the fork() to make child process in C++. We also do some calculation into each process. So in our parent process we will find sum of all even numbers of an array, and inside the child process we will count the odd sum from array elements.

When fork() is called, it returns a value. If the value is greater than 0, then currently it is in parent process, otherwise it is in child process. So using this we can distinguish between the processes.

Example Code

#include <iostream>
#include <unistd.h>
using namespace std;
int main() {
   int a[15] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 , 11, 12, 13, 14, 15};
   int odd_sum = 0, even_sum = 0, n, i;
   n = fork(); //subdivide process
   if (n > 0) { //when n is not 0, then it is parent process
      for (int i : a) {
         if (i % 2 == 0)
         even_sum = even_sum + i;
      }
      cout << "Parent process " << endl;
      cout << "Sum of even numbers: " << even_sum << endl;
   } else { //when n is 0, then it is child process
      for (int i : a) {
         if (i % 2 != 0)
            odd_sum = odd_sum + i;
      }
      cout << "Child process " <<endl;
      cout << "Sum of odd numbers: " << odd_sum << endl;
   }
   return 0;
}

Output

Parent process
Sum of even numbers: 56
Child process
Sum of odd numbers: 64
raja
Published on 04-Apr-2019 11:30:28
Advertisements