Fork () new process and write to files for child and parent processes
I am new to fork (), parent and child processes and have a hard time understanding the logic of the code I wrote but did not accomplish what I expected. Here's 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 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" is written twice in parent.out. If I remove the for loop entirely, then only one "Begin" is written, which is expected.
So I think it is because of fork () and definitely I am missing or not understanding some logic. Could you guys help me explain?
My plan is to be able to write something before the for loop in parent.out and write something during the for loop in parent.out. The child process will be written to child.out.
source to share
In C, I / O using a structure is FILE
buffered at the user process level. In your case, the output you wrote on fp_parent
was not actually written to disk and was stored in a local buffer at the moment fork
. fork
creates a copy of the entire process, including the buffer containing Begin
, and so it appears twice in your file. Try to put fflush(fp_parent);
up fork
. This will clear the buffer and the dirty line will disappear from the file.
source to share