
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Creating child process using fork() in Python
- Process vs Parent Process vs Child Process
- Creating multiple process using fork() in C
- Python program to communicate between parent and child process using the pipe.
- What are Java parent and child classes in Java?
- jQuery parent > child Selector
- fork() in C
- Parent and Child classes having same data member in Java
- Prevent fork bomb by limiting user process in linux
- Difference between fork() and exec() in C
- 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?
- Run Python script from Node.js using child process spawn() method?
- How to get the parent process of the Process API in Java 9?
Advertisements