0

I'm having trouble on school assignment, currently the code works on child getting and putting text to new text file. except for the parent, file created successfully but its empty.

my text files look like this

1 text to be copied to child1.

0 text to be copied to parent

and my codes are below

int main(){
    int c1,c2,c3 ;
    FILE *fp1,*fpm, *fp2;
    char str1[100];
    char str2[100];
    fp1 = fopen("test.txt","r");
    fpm = fopen("mainlog.txt","w");
    fp2 = fopen("child1log.txt","w");

    c1 = fork();
    if(c1 == 0){
        printf("child Process\n");
        while ((fgets(str1,80,fp1))!=NULL){
            if(str1[0]=='1'){
                fputs(str1+1,fp2);
            }
        }
    }
    else{
        printf("This is parent Process\n");
        while ((fgets(str,80,fp1))!=NULL){
            if(str[0]=='0'){
                fputs(str+1,fpm);
            }
        }
    }

    return 0;
}

Help is appreciated.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • The second line does not look like it starts with a "0". What should the parent do if the line it reads starts with a "1"? Or with a different letter than "0" or "1"? – Yunnosch May 08 '18 at 05:03
  • Would you notice if the parent has a "1" in first position? Change the program to notice and make a warning output. Same for non-digit or other digit. – Yunnosch May 08 '18 at 05:03
  • You might want to double check that the file quote we are seeing is appropriatly representing the text file which the program sees. – Yunnosch May 08 '18 at 05:04
  • In general debugging is your friend: https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ https://stackoverflow.com/questions/2069367/how-to-debug-using-gdb – Yunnosch May 08 '18 at 05:05

1 Answers1

1

The open file descriptor underlying fp1 points to an open file description (yes — that's the POSIX terminology; see open()). After the fork(), each process has its own open file descriptor for the file, but they share the open file description. And the read position is a property of the open file description.

Thus, one of the two processes gets to read first, and it moves the read pointer for the other process too. Since the first process reads all the data in the file, the second process gets EOF immediately.

You'd could open the file for reading after the fork(); at least, that's probably the simplest way to avoid trouble. Alternatively, the processes could rewind before reading. For one, that would be a no-op, but for the other it would make the difference. In this context, you could also read before the fork, which would populate the buffer for fp1 with the data and both processes would see what was read. That probably counts as cheating, though.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278