Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How would you write a program in c++ that uses fork and pipe to create processes

ID: 3723599 • Letter: H

Question

How would you write a program in c++ that uses fork and pipe to create processes to add up all numbers in a file. The user will enter a number (1, 2, or 4) of parallel processes to create for processing the numbers. The system will then create this many processes, evenly dividing the file contents between the processes. For example, if the file has 1000 numbers and the user wants 4 processes, then each process would process 250 numbers in the file.  

Parent process. This process allows user to input the number of processes to create (1, 2, or 4). It determines what portion of the file each process must work on and informs the process via a pipe. More specifically, the first child process handles the first block in the file, and the second child process handles the second one and so on. The parent then waits for each child to report its result. Once each result is received, it combines the results prints the overall result.

Child process. Receive which part of the file to calculate from the parent process through pipe. Process the file and send the result back to the parent process through pipe.

There are 4 given files named file1.dat, file2.dat, file3.dat, file4.dat

this program should output the result and record the run time for each process 1,2, and 4

Code is as follows:

Prog1.cpp

----------------------------------------

#include <unistd.h>

#include <stdio.h>

#include <iostream>

#include <fstream>

#include <cstring>

#include <sstream>

#include <time.h>

#define RUNS 1000

using namespace std;

int main()

{

int child_count = 1;

string line;

stringstream ss;   

time_t start,finish;

//Promp the user

cout << "Which file to use? ";

cin >> line;

cout << "How many child processes would you like to make [1, 2, 4] ";

cin >> child_count;

cout << "Computing Sum..." << endl;

char * cstr = new char [line.size()+1]; //Create C-String

strcpy (cstr, line.c_str()); //Copy line (file name) to the C-string

ifstream myfile (cstr); // Loads the file to read. Requires a C-String

int line_count = 0; // Number of Lines in the file or number count

int fds[child_count+1][2];//Stuff for the pipe.

if (myfile.is_open())

{

while ( myfile.good() )

{

getline (myfile,line); //Read Line

if(line != "")

{

line_count++; // increment line count

}

}

int numbers[line_count]; // Instantiate an array of numbers

ifstream myfile (cstr); // Re-Load the file to insert values into the array

int x = 0;

while ( myfile.good() )

{

getline (myfile,line);

if(line != "")

{

ss << line;

ss >> numbers[x];

x++;

}

}

start = time(NULL); // Start our timer for calculating run time.

// The loop for running to the program.

for(int n = 0; n < RUNS; n++) {

pipe(fds[child_count]); //We're using the last File Descriptor for Child -> Parent

  

for(int x = 0; x < child_count; x++)

{

pipe(fds[x]); // Instantiate the pipe

int indexes[2]; //This is an array of integers that determine the begginning and end of the Child's loop

indexes[0] = ((x)*(line_count/child_count)); //The beginning index

indexes[1] = ((x+1)*(line_count/child_count)); //The ending index

write(fds[x][1], &indexes, 2*sizeof(int)); //Send our array of indexes to child

if(fork() == 0) //If it is child

{

int temp = 0; //Temp variable for the sum

int indexes2[2];

read(fds[x][0], &indexes2, 2*sizeof(int)); //Read the index's from pipe   

for(int k = indexes2[0]; k < indexes2[1] ; k++)

{

temp += numbers[k];

}

//Write the child's partion of the sum to the pipe

write(fds[child_count][1], &temp, sizeof(int));

_exit(0); //Exit the child process

}

}

int tmp, total;

total = 0;

for(int m =0; m < child_count; m++) {

read(fds[child_count][0], &tmp, sizeof(int));

total += tmp;

}

cout << "DONE Calculating!" << endl;

// cout << "TIME TOOK TO CALCULATE: " << time << " microseconds" << endl;

cout << "TOTAL OF NUMBERS: " << total << endl;

}

finish = time(NULL);

cout << "START " << start << " FINISH " << finish << endl;

float runtime = (float)((finish - start))/(RUNS);

cout << "AVERAGE RUN TIME: " << runtime << " seconds!" << endl;

cout << "EOP" << endl;

}

else

{

cout << "File Unable to Open!" << endl;  

}

}

---------------------------------------------

Prog2.cpp

---------------------------------------------

#include <unistd.h> // for fork() and pipe()
#include <stdlib.h> // for exit()
#include <sys/wait.h> // for wait()
#include <fstream> // for functions related to files
#include <cstring> // for string functions

int main()

{

int fd1[2]; // Used to store two ends of first pipe

int fd2[2]; // Used to store two ends of second pipe

char fixed_str[] = "forgeeks.org";

char input_str[100];

pid_t p;

if (pipe(fd1)==-1)

{

fprintf(stderr, "Pipe Failed" );

return 1;

}

if (pipe(fd2)==-1)

{

fprintf(stderr, "Pipe Failed" );

return 1;

}

scanf("%s", input_str);

p = fork();

if (p < 0)

{

fprintf(stderr, "fork Failed" );

return 1;

}

else if (p > 0)

{

char concat_str[100];

close(fd1[0]); // Close reading end of first pipe

write(fd1[1], input_str, strlen(input_str)+1);

close(fd1[1]);

wait(NULL);

close(fd2[1]); // Close writing end of second pipe

read(fd2[0], concat_str, 100);

printf("Concatenated string %s ", concat_str);

close(fd2[0]);

}

else

{

close(fd1[1]); // Close writing end of first pipe

char concat_str[100];

read(fd1[0], concat_str, 100);

int k = strlen(concat_str);

int i;

for (i=0; i<strlen(fixed_str); i++)

concat_str[k++] = fixed_str[i];

concat_str[k] = ''; // string ends with ''

close(fd1[0]);

close(fd2[0]);

write(fd2[1], concat_str, strlen(concat_str)+1);

close(fd2[1]);

exit(0);

}

}

-------------------------------------------

there are two main class but our professor told us there should be only one main class.

need help to write these two main classes as one main class.

need answer ASAP

Explanation / Answer

Ans :

                In the two programs given, the first program is getting compiled successfully whereas the second one is not as the required header files were not included. PFB entire code along with required header files and the compile log of both the programs.

Programming code 1 :

#include <unistd.h>

#include <stdio.h>

#include <iostream>

#include <fstream>

#include <cstring>

#include <sstream>

#include <time.h>

#define RUNS 1000

using namespace std;

int main()

{

int child_count = 1;

string line;

stringstream ss;   

time_t start,finish;

//Promp the user

cout << "Which file to use? ";

cin >> line;

cout << "How many child processes would you like to make [1, 2, 4] ";

cin >> child_count;

cout << "Computing Sum..." << endl;

char * cstr = new char [line.size()+1]; //Create C-String

strcpy (cstr, line.c_str()); //Copy line (file name) to the C-string

ifstream myfile (cstr); // Loads the file to read. Requires a C-String

int line_count = 0; // Number of Lines in the file or number count

int fds[child_count+1][2];//Stuff for the pipe.

if (myfile.is_open())

{

while ( myfile.good() )

{

getline (myfile,line); //Read Line

if(line != "")

{

line_count++; // increment line count

}

}

int numbers[line_count]; // Instantiate an array of numbers

ifstream myfile (cstr); // Re-Load the file to insert values into the array

int x = 0;

while ( myfile.good() )

{

getline (myfile,line);

if(line != "")

{

ss << line;

ss >> numbers[x];

x++;

}

}

start = time(NULL); // Start our timer for calculating run time.

// The loop for running to the program.

for(int n = 0; n < RUNS; n++) {

pipe(fds[child_count]); //We're using the last File Descriptor for Child -> Parent

  

for(int x = 0; x < child_count; x++)

{

pipe(fds[x]); // Instantiate the pipe

int indexes[2]; //This is an array of integers that determine the begginning and end of the Child's loop

indexes[0] = ((x)*(line_count/child_count)); //The beginning index

indexes[1] = ((x+1)*(line_count/child_count)); //The ending index

write(fds[x][1], &indexes, 2*sizeof(int)); //Send our array of indexes to child

if(fork() == 0) //If it is child

{

int temp = 0; //Temp variable for the sum

int indexes2[2];

read(fds[x][0], &indexes2, 2*sizeof(int)); //Read the index's from pipe   

for(int k = indexes2[0]; k < indexes2[1] ; k++)

{

temp += numbers[k];

}

//Write the child's partion of the sum to the pipe

write(fds[child_count][1], &temp, sizeof(int));

_exit(0); //Exit the child process

}

}

int tmp, total;

total = 0;

for(int m =0; m < child_count; m++) {

read(fds[child_count][0], &tmp, sizeof(int));

total += tmp;

}

cout << "DONE Calculating!" << endl;

// cout << "TIME TOOK TO CALCULATE: " << time << " microseconds" << endl;

cout << "TOTAL OF NUMBERS: " << total << endl;

}

finish = time(NULL);

cout << "START " << start << " FINISH " << finish << endl;

float runtime = (float)((finish - start))/(RUNS);

cout << "AVERAGE RUN TIME: " << runtime << " seconds!" << endl;

cout << "EOP" << endl;

}

else

{

cout << "File Unable to Open!" << endl;  

}

}

Programming code 2 :

#include <unistd.h> // for fork() and pipe()
#include <stdlib.h> // for exit()
#include <sys/wait.h> // for wait()
#include <fstream> // for functions related to files
#include <cstring> // for string functions

int main()

{

int fd1[2]; // Used to store two ends of first pipe

int fd2[2]; // Used to store two ends of second pipe

char fixed_str[] = "forgeeks.org";

char input_str[100];

pid_t p;

if (pipe(fd1)==-1)

{

fprintf(stderr, "Pipe Failed" );

return 1;

}

if (pipe(fd2)==-1)

{

fprintf(stderr, "Pipe Failed" );

return 1;

}

scanf("%s", input_str);

p = fork();

if (p < 0)

{

fprintf(stderr, "fork Failed" );

return 1;

}

else if (p > 0)

{

char concat_str[100];

close(fd1[0]); // Close reading end of first pipe

write(fd1[1], input_str, strlen(input_str)+1);

close(fd1[1]);

wait(NULL);

close(fd2[1]); // Close writing end of second pipe

read(fd2[0], concat_str, 100);

printf("Concatenated string %s ", concat_str);

close(fd2[0]);

}

else

{

close(fd1[1]); // Close writing end of first pipe

char concat_str[100];

read(fd1[0], concat_str, 100);

int k = strlen(concat_str);

int i;

for (i=0; i<strlen(fixed_str); i++)

concat_str[k++] = fixed_str[i];

concat_str[k] = ''; // string ends with ''

close(fd1[0]);

close(fd2[0]);

write(fd2[1], concat_str, strlen(concat_str)+1);

close(fd2[1]);

exit(0);

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote