C++ 中使用 fork() 在父程序和子程序中進行計算


在本部分中,我們將看到如何在 C++ 中使用 fork() 來建立子程序。我們還在每個程序中進行一些計算。因此,在我們的父程序中,我們將找到一個數組的偶數總和,而在子程序中,我們將從陣列元素中統計奇數總和。

當呼叫 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

更新於:2019-07-30

2K+ 瀏覽

開啟 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.