Why is this plug-in program printed twice?

According to my understanding fork() , this should print "Hello, World!". once since there is only one process before calling fork . However, it prints twice. Curiously, if I add the string \n to the string or use puts() instead of printf() , it will print only once.

 #include<unistd.h> #include<stdio.h> int main() { printf("Hello, World!"); fork(); } 
+5
source share
3 answers

Buffering.

Since the standard output on your system is buffered by default, it does not print immediately. The buffer, however, will be flushed before the process exits.

Since fork copies the full memory space of the parents, the state of the file descriptor, etc., it also copies the buffer data that needs to be printed.

Thus, if you do not explicitly flush the standard output buffer before forcing (by adding \n to the output or calling fflush(stdout); ), both processes will have buffered output for printing. A.

+4
source

Explanation I can provide:

printf("Hello, World!"); does not print immediately because the output is not flushed to stdout .

when fork() copies the memory of a process, it copies the internal buffers, and when both processes terminate, both processes clear their buffers and the text is displayed twice.

+2
source

The output to stdout (which is where printf writes its output) is, by default, buffered by line. This means that its buffer will be cleared (and actually written to the output) when a new line is printed (or the buffer is full).

If you do not print a new line, then the buffered output will be duplicated by the child process, and both the parent and the child process will each reset their own buffer when the processes are completed, which will lead to the printing of two outputs.

+2
source

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


All Articles