使用fork()在父进程和子进程中进行计算

编写一个程序,在父进程中求偶数之和,在子进程中求奇数之和。

null

例如:

Input : 1, 2, 3, 4, 5 Output :Parent process Sum of even no. is 6Child process Sum of odd no. is 9 

说明: 在这里,我们使用了 fork() 函数创建两个进程一个子进程和一父进程。

  • 对于子进程fork() 返回0 所以我们可以计算子过程中所有奇数的和。
  • fork()返回值 大于0 对于父进程,我们可以计算和
  • 对于所有偶数,只需检查fork()返回的值即可。

C++

// C++ program to demonstrate calculation in parent and
// child processes using fork()
#include <iostream>
#include <unistd.h>
using namespace std;
// Driver code
int main()
{
int a[10] = { 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 " ;
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 " ;
cout << "Sum of odd no. is " << sumOdd << endl;
}
return 0;
}


输出:

Parent process Sum of even no. is 30Child process Sum of odd no. is 25

本文由 Pushpanjali Chauhan .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享