In: Computer Science
Use c++ programming Construct an array of 1000 random integers within range [0, 100] An input file input.txt is provide. Each line of input.txt is a query integer that you need to check how many of that number is in your random integer array. For each query integer, fork a new child process to do the counting. The output is for each input query, output the count and child process id. For example: $> query: 13 count: 5 pid: 13342 $> query: 22 count: 3 pid: 13357 Here is the input.txt 5 13 24 6 17 20 1 51 36 42 2 19 67 35 64 91 96 84 72
Use c++ programming
Solution:
first make a text file with name "input.txt" and write the content to the file:
10
20
30
40
50
60
Make sure each number is in one line and file is accessible to the program.
Now, run the following program,
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include<stdio.h>
using namespace std;
int main(int argc, char *argv[])
{
int arr[1000];
int number;
char line[10];
pid_t pid;
FILE *f = fopen("input.txt", "r"); //opening file
//generating numbers
srand(time(0)); //seed to random number generator
for(int i = 0; i<1000; i++)
arr[i] = rand() % 101;
cout<<endl;
while( fgets(line, 10, f) )
{
sscanf(line, "%d", &number); //reading the number
pid = fork();
if ( pid == 0 )
{
int count = 0, index = 0;
while( index<1000 )
{
if( arr[index] == number )
count++;
index++;
}
cout<<"query: "<<number<<"\tcount: "<<count<<"\tpid: "<<getpid()<<endl;
fclose(f);
exit(1);
}
else
{
wait(NULL);
}
}
cout<<endl;
return 0;
}
Output:
Please give thumbsup, if you like it. Thanks.