Thread: Problem forking child processes

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    1

    [SOLVED] Problem forking child processes

    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.
    Last edited by md5fungi; 10-25-2009 at 02:21 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Why isn't the execlp() function doing anything?
    By jsrig88 in forum C Programming
    Replies: 5
    Last Post: 10-12-2009, 10:09 AM
  2. Replies: 7
    Last Post: 02-06-2009, 12:27 PM
  3. Problem w/ CreateWindowEx and child window
    By Rutabega in forum Windows Programming
    Replies: 0
    Last Post: 06-29-2005, 10:59 AM
  4. Problem using java programs within C code
    By lemania in forum Linux Programming
    Replies: 1
    Last Post: 05-08-2005, 02:02 AM
  5. freeing problem with concurrent processes
    By alavardi in forum C Programming
    Replies: 2
    Last Post: 03-07-2005, 01:09 PM