Question: C++, Unix, Fork(), Pipe(), File descriptors? For this project we prompt the user for a file and the number of child processes. The files have

C++, Unix, Fork(), Pipe(), File descriptors?

For this project we prompt the user for a file and the number of child processes. The files have a number on each line in the file. We then create that number of forks and split the lines in the file equally.Then write the partial sum to the pipe. Then have the parrent print out the total sum.

Question: My text book gose over forks but never explains pipe-ing, how could I get a child to read/sum lines 1-250 and another lines 251-500 and then get the parrent to read them? Any hits or example code would help thanks.

#include

#include

#include

#include

#include

#include

#include

#include

using namespace std;

int main ()

{

// variables

int numPros;

string givenFile;

pid_t pid;

int numLine;

char *s, buf[1024];

int fds[2];

//Promt user input

cout << "Choose 1, 2, or 4 processes to use: " << endl;

cin >> numPros;

//Handle incorect user input

while (!(numPros==1) && !(numPros==2) && !(numPros==4))

{

cout << "Invalid entry! Please enter a valid number of processes: " << endl;

cin >> numPros;

}

//get file

cout << "Choose a file: " << endl;

cout << "[file1.dat, file2.dat, file3.dat, file4.dat]" << endl;

cin >> givenFile;

//Handle incorect user input

while (!(givenFile=="file1.dat") && !(givenFile=="file2.dat") && !(givenFile=="file3.dat") && !(givenFile=="file4.dat"))

{

cout << "Invalid entry! Please enter a valid number of processes: " << endl;

cin >> givenFile;

}

//get number of line in file

int x;

ifstream inFile;

inFile.open(givenFile.c_str());

int y = 0;

while (inFile >> x) {

y = y + 1;

}

numLine = y;

inFile.close();

//User feadback

cout << givenFile + " will be sumed using " << numPros << " processes, spliting " << numLine << " lines" << endl;

//fork

for (int i = 0; i < numPros; i++){

//pipe(fds);

pid = fork();

//Handle error

if (pid == -1)

{

perror ("fork");

}

//child

if (pid == 0)

{

cout << "child:" << pid << endl;

//write(fds[1], s, 12);

exit(0);

}

//parrent

if (pid > 0)

{

if ( wait(0) == -1)

{

perror ("wait");

}

//read(fds[0], buf, 12);

//write(1, buf, 12);

cout << "parent:" << pid << endl;

}

}

return 0;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!