简体   繁体   中英

Fork() new process and write to files for child and parent processes

I'm new to fork(), parent and child processes and have some difficulty understanding the logic behind the code that I wrote, but did not perform what I expected. Here is what I have:

 int main (int argc, char** argv)
 {
     FILE *fp_parent;
     FILE *fp_child;

     fp_parent = fopen ("parent.out","w");
     fp_child = fopen ("child.out","w");

     int test_pid;
     printf ("GET HERE\n");

     fprintf (fp_parent,"Begin\n"); // MY CONCERN

     for (int i = 0; i < 1; i++) //for simplicity, just fork 1 process.
     {                          // but i want to fork more processes later
        test_pid = fork();
        if(test_pid < 0)
        {
          printf ("ERROR fork\n");
          exit (0);
        }
        else if(test_pid == 0) // CHILD
        {
          fprintf(fp_child,"child\n");
          break;
        }
        else //PARENT
        {
          fprintf(fp_parent,"parent\n");
        }
     }
     fclose(fp_parent);
     fclose(fp_child);
 }

So the output of above code is:

 to stdout: GET HERE

 in parent.out:

 Begin

 parent

 Begin

 in child.out:

 child

My main concern is that I don't quite understand why "Begin" get written to parent.out twice. If I remove the for loop completely, then only one "Begin" is written which is expected.

So I think that it's because of the fork() and definitely I miss or don't understand some logic behind it. Could you guys please help me explain?

My plan to be able to write something before the for loop in parent.out and write something during the for loop in parent.out. Child process will write to child.out.

In C, the input/output operations using FILE structure are buffered at the level of user process. In your case, the output you have written to fp_parent was not actually written onto the disk and was kept in a local buffer at the moment of fork . The fork creates a copy of the whole process including the buffer containing Begin and this is why it appears twice in your file. Try to put fflush(fp_parent); before the fork . This will flush the buffer and the dirty line will disappear from the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM