在fork()中搜索

先决条件—— C中的fork() , fork()中的排序 问题陈述 –编写程序搜索父进程中的关键元素,并打印子进程中要搜索的关键元素。

null

示例——

Input :
Key = 10;
array[5] = {3, 8, 4, 10, 80};

Output: 
Parent process 
key is  present in array
Child process 
numbers to be search is 10

解释 -在这里,我们使用了 叉子() 函数创建两个进程一个子进程和一父进程。

  • fork()为父进程返回大于0的值,以便执行 搜索 活动
  • for child process fork()返回0,这样我们就可以打印要搜索的键的值。
  • 这里我们使用一个简单的搜索算法来搜索给定数组中的关键元素。
  • 我们使用fork()的返回值来知道哪个进程是子进程,哪个是父进程。

注—— 在某些情况下,子进程不必首先执行,或者父进程将首先被分配CPU,任何进程都可能在某个时间段被分配CPU。此外,在不同的执行过程中,进程id可能会有所不同。

代码–

// C++ program to demonstrate searching
// in parent and printing result
// in child processes using fork()
#include <iostream>
#include <unistd.h>
using namespace std;
// Driver code
int main()
{
int key = 10;
int id = fork();
// Checking value of process id returned by fork
if (id > 0)  {
cout << "Parent process " ;
int a[] = { 3, 8, 4, 10, 80 };
int n = 5;
int flag;
int i;
for (i = 0; i < n; i++)
{
if (a[i] != key) {
flag = 0;
}
else {
flag = 1;
}
}
if (flag == 1) {
cout << "key is not present in array" ;
}
else {
cout << "key is present in array" ;
cout << "" ;
}
}
// If n is 0 i.e. we are in child process
else {
cout << "Child process " ;
cout << "numbers to be search is " ;
cout << key;
}
return 0;
}


输出——

Parent process 
key is  present in array
Child process 
numbers to be search is 10

本文由 Pushpanjali Chauhan .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享