Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this program with fork print twice? [duplicate]

Tags:

c

fork

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();
}
like image 271
Brian McCutchon Avatar asked Mar 09 '17 08:03

Brian McCutchon


3 Answers

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.

like image 178
StoryTeller - Unslander Monica Avatar answered Oct 26 '22 00:10

StoryTeller - Unslander Monica


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.

like image 31
Jean-François Fabre Avatar answered Oct 26 '22 01:10

Jean-François Fabre


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.

like image 31
Some programmer dude Avatar answered Oct 26 '22 02:10

Some programmer dude