Duplicate numbers printed by child process

Viewed 37

I am trying to create a child process for each of the inner loop, but I keep getting duplicated results. I guess this is because the child processes created after each iteration try to access the same file for the same piece of data. How do I stop them from obtaining duplicated numbers? data.txt contains only 1 integer which is 1:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
    FILE *fptr;
    int N, i, j;
    //each of the process obtaining 200 integers from file a.txt
    pid_t pid;
    for(i=0;i<200;i++) {
    //loop for performing the given 8 steps by each process
        for(j=1;j<4;j++){
            pid= fork();
            fptr = fopen("data.txt","r");//step 1
            fscanf(fptr,"%d",&N);//step 2
            fclose(fptr);//step 3
            printf("N=%d ProcessId=P%d\n", N, j);//step 4
            N=N+1;//step 5
            fptr = fopen("data.txt","w");//step 6
            fprintf(fptr,"%d",N);//step 7
            fclose(fptr);//step 8
        }
    }
    return 0;
}
0 Answers
Related