Question
C++, Unix, Fork(), Pipe(), multiple childs? For this project we prompt the user for a file and the number of child processes. The files have
C++, Unix, Fork(), Pipe(), multiple childs?
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: I don't understand how to create multiple childs without creating multiple parents. Any help would be useful 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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started