Calculation in Parent and Child Process Using Fork in C++



The fork() function creates a new process by duplicating the current one. It allows developers to perform parallel tasks and manage resources efficiently.

When fork() is called, it returns a value. If the value is greater than 0, then it is in the parent process. Otherwise, it is in the child process.

In this C++ article, we will learn how to use the fork() system call to perform calculations in parent and child processes.

According to the problem statement, we will do calculations. So, in our parent process, we will find the sum of all even numbers in an array, and inside the child process, we will calculate the odd sum from the array elements.

Example of Calculation in Parent and Child Process using fork()

In the following example, we use the fork() function to calculate the sum of all even numbers and odd numbers, respectively, in the parent and child processes -

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

Following is the output -

Parent process 
Sum of even numbers: 56
Child process 
Sum of odd numbers: 64
Updated on: 2025-05-15T15:44:05+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements