I've been working on this code for quite a long time now, and I still can't seem to find out my problem. I'm trying to split a file that contains integers into 4 pieces, have each child process sum them, and then eventually pipe them to the parent process.
I've rewritten this program many ways, but my problem is always the same; I can get the first child process to sum its numbers, but the other child processes end up printing "0" for their individual sums.
Any ideas? (Note: I understand that the if-statement logic in the child process may be somewhat convoluted to understand, but I have double-checked it, and it works for the first child process)
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;
cout << current_number[i] << endl;
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;
}
edit:
NVM, current_number[i]++ should be outside the "if" loop. SOLVED.