Multiple child processes accessing the same vector

38 views Asked by At

I want to create a vector with 10,000 elements, set them to 5, and then create 10 child processes that do a mathematical operation on a section of that vector, and return the sum of all the elements in that section.

I'm using a vector sums of size 10 to store the sum of each section. But for some reason, when I print the sums on each child, only the element of the correspondent index has the correct value.

#include  <stdio.h>
#include  <stdlib.h>
#include  <unistd.h>
#include  <sys/wait.h>

#define VECTOR_SIZE 10000
#define INITIAL_VALUE 5
#define SECTION_SIZE 1000

int do_operations(int vetor[], int section_index);
int sum_all(int sums[]);

int main() {
    // IInitializing the vector
    int vetor[VECTOR_SIZE];
    for (int i = 0; i < VECTOR_SIZE; i++) {
        vetor[i] = INITIAL_VALUE;
    }

    // Doing the operations
    int sums[VECTOR_SIZE/SECTION_SIZE];
    int status;

    for(int n = 0; n < 10; n++){
        if (fork() != 0) { 
            /* Parent */
            waitpid( -1, &status, 0); 
        }
        else {
            /* Child */
            sums[n] = do_operations(vetor, n);
            printf("Sum of Section %d: %d\n", n, sums[n]);
            exit(0);
        }
    }

    printf("Sum of all sections: %d\n", sum_all(sums));
    return 0;
}

Current output:

Sum of Section 0: 10000
Sum of Section 1: 10000
Sum of Section 2: 10000
Sum of Section 3: 10000
Sum of Section 4: 10000
Sum of Section 5: 10000
Sum of Section 6: 10000
Sum of Section 7: 10000
Sum of Section 8: 10000
Sum of Section 9: 10000
Sum of all sections: 0

Expected output:

Sum of Section 0: 10000
Sum of Section 1: 10000
Sum of Section 2: 10000
Sum of Section 3: 10000
Sum of Section 4: 10000
Sum of Section 5: 10000
Sum of Section 6: 10000
Sum of Section 7: 10000
Sum of Section 8: 10000
Sum of Section 9: 10000
Sum of all sections: 100000
0

There are 0 answers