According to my understanding of fork()
, this should print "Hello, World!" once, since there is only one process before fork
is called. However, it prints twice. Curiously, if I add a \n
to the string or use puts()
instead of printf()
, it only prints once.
#include<unistd.h>
#include<stdio.h>
int main() {
printf("Hello, World!");
fork();
}
Buffering.
Since standard output on your system is buffered by default, it doesn't print immediately. The buffer will however be flushed before the process is exited.
Since fork
copies the parents entire memory space, file descriptor state, etc, it will also copy the buffered data that needs to be printed.
As such, unless you explicitly flush the standard output buffer before forking (by appending \n
to the output or calling fflush(stdout);
), both processes will have buffered output to print.
The explanation I can provide:
printf("Hello, World!");
doesn't print at once because output is not flushed to stdout
.
when fork()
copies process memory, it copies internal buffers, and when both processes terminate, both processes flush their buffers and the text is outputted twice.
Output to stdout
(which is where printf
writes it output) is by default line buffered. That means its buffer will be be flushed (and actually written to the output) when you print a newline (or the buffer gets full).
If you don't print a newline, then the buffered output will be duplicated by the child process, and both the parent and child process will each flush its own buffer when the processes ends, leading to two outputs being printed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With