
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Calculation in parent and child process using fork() in C++
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
- Related Articles
- Creating child process using fork() in Python
- Process vs Parent Process vs Child Process
- Python program to communicate between parent and child process using the pipe.
- Creating multiple process using fork() in C
- What are Java parent and child classes in Java?
- jQuery parent > child Selector
- Parent-Child Interaction Therapy: Meaning And Application
- Parent and Child classes having same data member in Java
- Prevent fork bomb by limiting user process in linux
- How to remove all child nodes from a parent using jQuery?
- How to get the child element of a parent using JavaScript?
- How to call parent constructor in child class in PHP?
- How to remove all child nodes from a parent node using jQuery?
- How to transfer data from parent to child component using Angular 8?
- Using Calculation views inside another calculation view in SAP HANA

Advertisements