在父级和子级进程中使用C ++中的fork()进行计算

在本节中,我们将看到如何fork()在C ++中使用制作子进程。我们还对每个过程进行了一些计算。因此,在父进程中,我们将找到数组的所有偶数之和,而在子进程中,我们将计算数组元素中的奇数和。

fork()被调用时,它返回一个值。如果该值大于0,则当前处于父进程中,否则处于子进程中。因此,使用它我们可以区分过程。

范例程式码

#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;
}

输出结果

Parent process
Sum of even numbers: 56
Child process
Sum of odd numbers: 64