编写一个程序来创建4个进程:执行各种任务的父进程及其子进程:
null
- 父进程计数一个数字的频率
- 第一个子数组排序
- 第二个子项查找给定数组中的偶数总数
- 第三个子计算数组中偶数的和
例如——
Input : 2, 4, 6, 7, 9, 0, 1, 5, 8, 3 Output : Parent process : the key to be searched is 7 the frequency of 7 is 1 1st child process : the sorted array is 0 1 2 3 4 5 6 7 8 9 2nd child process : Total even no are: 5 3rd child process : the sum is :45
解释—— 在这里,我们使用fork()函数创建了4个进程,三个子进程和一个父进程。所以,这里我们使用两个fork()函数来创建4个进程n1=fork()和n2=fork()
- 如果n1和n2大于零,则计算数字频率的是父进程。
- 如果n1等于零,n2大于零,则对给定数组进行排序的是第一个子进程。
- 如果n1大于零,n2等于零,则第二个子进程将查找数组中的偶数总数。
- 如果n1和n2都等于零,则第三个子元素计算数组中所有元素的和。
代码–
// C++ code to demonstrate the calculation // in parent and its 3 child processes using fork() #include <iostream> #include <unistd.h> using namespace std; int main() { int a[10] = { 2, 4, 6, 7, 9, 0, 1, 5, 8, 3 }; int n1, n2, i, j, key, c, temp; n1 = fork(); n2 = fork(); // if n1 is greater than zero // and n2 is greater than zero // then parent process executes if (n1 > 0 && n2 > 0) { int c = 0; cout << "Parent process :" << endl; // key to be searched is 7 key = 7; cout << "the key to be searched is " << key << endl; for (i = 0; i < 10; i++) { if (a[i] == key) // frequency of key c++; } cout << "the frequency of " << key << " is " << c << endl; } // else if n1 is zero // and n2 is greater than zero // then 1st child process executes else if (n1 == 0 && n2 > 0) { cout << "1st child process :" << endl; for (i = 0; i < 10; i++) { for (j = 0; j < 9; j++) { if (a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } cout << "the sorted array is" << endl; for (i = 0; i < 10; i++) { cout << a[i] << " " ; } cout << endl; } // else if n1 is greater than zero // and n2 is zero // then 2nd child process executes else if (n1 > 0 && n2 == 0) { int f = 0; cout << "2nd child process :" << endl; for (i = 0; i < 10; i++) { // counting total even numbers if (a[i] % 2 == 0) { f++; } } cout << " Total even no are: " << f << " " ; cout << endl; } // else if n1 is zero // and n2 is zero // then 3rd child process executes else if (n1 == 0 && n2 == 0) { cout << "3rd child process :" << endl; int sum = 0; // summing all given keys for (i = 0; i < 10; i++) { sum = sum + a[i]; } cout << "the sum is :" << sum << endl; } return 0; } |
输出——
Parent process : the key to be searched is 7 the frequency of 7 is 1 1st child process : the sorted array is 0 1 2 3 4 5 6 7 8 9 2nd child process : Total even no are: 5 3rd child process : the sum is :45
本文由 希瓦尼·巴格尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。或
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END