Skip to content
Related Articles
Calculation in parent and child process using fork()
• Difficulty Level : Easy
• Last Updated : 29 Aug, 2017

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 10
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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++ program to demonstrate calculation in parent and``// child processes using fork()``#include ``#include ``using` `namespace` `std;`` ` `// Driver code``int` `main()``{``    ``int` `a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };``    ``int` `sumOdd = 0, sumEven = 0, n, i;``    ``n = fork();`` ` `    ``// Checking if n is not 0``    ``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;``    ``}`` ` `    ``// If n is 0 i.e. we are in child process``    ``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
```

This article is contributed by Pushpanjali Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up