Statement before printing fork () twice

I experimented with fork() and redirected to check if the repeated instructions made by the parent apply to the child. I wrote the following simple program

 #include<stdio.h> #include<unistd.h> #include<stdlib.h> int main () { freopen( "error.txt", "w+t", stdout ); // From now on, stdout = error.txt printf (" ERROR! WHY DONT U UNDERSTAND?\n"); if ( fork() == 0 ) { printf(" I AM CHILD\n"); exit(0); } else- { printf (" EITHER I AM A PARENT OR SOMETHING GOT SCREWED\n"); } return 0; } 

The output ( error.txt ) I received is

 ERROR! WHY DONT U UNDERSTAND? EITHER I AM A PARENT OR SOMETHING GOT SCREWED ERROR! WHY DONT U UNDERSTAND? I AM CHILD 

Surprisingly, ERROR! WHY DONT U UNDERSTAND? ERROR! WHY DONT U UNDERSTAND? prints twice , even if it appears much earlier than fork() is called and should be printed only once by the parent.

Can anyone shed some light on this?

+6
source share
4 answers

Since the stream is not interactive after reopen , it is fully buffered and not painted over with '\n' . Before fork is called, the buffer still contains the message, and after fork this buffered message was duplicated (because both processes received their own copies of stdout ) and then blurred by both the parent and the child. See Section 7.19.3 of Standard C.

You can avoid this behavior by calling fflush just before fork .

+10
source

This is due to buffering. Do fflush right after printf .

Both processes end with the same copy of stdio 's internal content, and both continue to flush it to exit . You can also prevent it if you call _exit on the child.

+3
source

flushing the buffer will solve the problem. use fflush immediately after printing is approved. A.

+1
source

It seems like ERROR! WHY DONT U UNDERSTAND ERROR! WHY DONT U UNDERSTAND is still buffered after forked and recorded by both processes.

If you add

 fflush(stdout); 

right after the first printf() internal buffer is flushed and it appears only once in your file.

0
source

Source: https://habr.com/ru/post/916345/


All Articles