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

📅  最后修改于: 2021-05-30 03:46:04             🧑  作者: Mango

编写程序以在父进程中查找偶数之和,在子进程中查找奇数之和。

例子:

Input : 1, 2, 3, 4, 5 

Output :
Parent process 
Sum of even no. is 6
Child process 
Sum of odd no. is 10

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

  • 对于子进程fork()返回0,因此我们可以计算子进程中所有奇数的总和。
  • fork()对于父进程返回大于0的值,因此我们可以计算总和
  • 只需检查fork()返回的值即可得到所有偶数。
// C++ program to demonstrate calculation in parent and
// child processes using fork()
#include 
#include 
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 \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;
}

输出:

Parent process 
Sum of even no. is 30
Child process 
Sum of odd no. is 25
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”