Calculation in parent and child process using fork()
Last Updated :
13 Sep, 2021
Write a program to find sum of even numbers in parent process and sum of odd numbers in child process.
Examples:
Input : 1, 2, 3, 4, 5
Output :
Parent process
Sum of even no. is 6
Child process
Sum of odd no. is 9
Explanation: Here, we had used fork() function to create two processes one child and one parent process.
- For child process fork() returns 0 so we can calculate sum of all odd numbers in child process.
- fork() returns value greater than 0 for parent process so we can calculate sum
- for all even numbers there by just simply checking the value returned by fork().
C++
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sumOdd = 0, sumEven = 0, n, i;
n = fork();
if (n > 0) {
for (i = 0; i < 10; i++) {
if (a[i] % 2 == 0)
sumEven = sumEven + a[i];
}
cout << "Parent process \n" ;
cout << "Sum of even no. is " << sumEven << endl;
}
else {
for (i = 0; i < 10; i++) {
if (a[i] % 2 != 0)
sumOdd = sumOdd + a[i];
}
cout << "Child process \n" ;
cout << "\nSum of odd no. is " << sumOdd << endl;
}
return 0;
}
|
Output:
Parent process
Sum of even no. is 30
Child process
Sum of odd no. is 25
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...