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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP