- #1
md5fungi
- 24
- 0
Homework Statement
Need to split a file up into four parts, have four child processes assigned to a different part and sum that part, and then send the data to the parent process, which will then sum the four sums.
Homework Equations
Basic Fork() Knowledge and C++ Knowledge.
The Attempt at a Solution
I keep on having the same problem, regardless of how I code the program. The first child process does what it should, but the second, third, and fourth just print 0 for a sum. There must be some fundamental misunderstanding of the material I have, but I can't figure out what that is.
Code:
#include <iostream>
#include <unistd.h>
#include <fstream>
#include <sys/wait.h>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int i,n=0,total_numbers=0,number, status, split_numbers;
int previous_number[4];
int my_number[4];
int current_number[4] = {1,1,1,1};
int sum[4] = {0,0,0,0};
pid_t pid;
ifstream myfile;
myfile.open("test.dat");
while (myfile >> number) {
total_numbers++;
}
split_numbers = total_numbers/4;
myfile.close();
pid = fork();
for (i=0; i<4; i++) {
if (pid == 0) {
cout << "Child Process " << i << " " << getpid() << endl;
myfile.open("test.dat");
my_number[i] = split_numbers * (i+1);
previous_number[i] = split_numbers * i + 1;
while (myfile >> number) {
if (my_number[i] >= current_number[i] && previous_number[i] <= current_number[i]) {
sum[i]+=number;
current_number[i]++;
}
}
cout << sum[i] << endl;
myfile.close();
exit(0);
} else {
waitpid(pid, &status, 0);
cout << "Parent Process " << getpid() << endl;
pid = fork();
}
}
return 0;
}