Does this produce 16 copies of hello
? If not, how many?
#include <stdio.h>
#include <unistd.h>
int main(void)
{
printf("hello\n");
fork();
fork();
fork();
fork();
return(0);
}
Does this produce 16 copies of hello
? If not, how many?
#include <stdio.h>
#include <unistd.h>
int main(void)
{
printf("hello\n");
fork();
fork();
fork();
fork();
return(0);
}
It depends on whether you send the output to a file or pipe it to a program such as cat
(or wc -l
) or whether you leave it to write to the terminal. If it goes to the terminal, you should get just one line printed; if it goes to a pipe or file, you'll get 16.
See also printf()
anomaly after fork()
.
The difference is that when the output goes to the terminal, it is line-buffered; when it goes to a 'non-interactive device' (file, pipe), it is fully-buffered.
When the output is line-buffered, the newline in the format forces the output to appear before any of the fork()
calls is executed. There is nothing left for any of the processes to print.
When the output is fully buffered, the printf()
doesn't force the buffered data to the output. Each of the 16 processes created from the 4 consecutive fork()
calls has a copy of the same buffer, waiting to be flushed. When the processes exit, those buffers are flushed, and therefore 16 copies of the output appear.
See C11 §7.21.3 Files ¶3 and ¶7 for the standard specification.
Since fork();
is called after the print statement. There will be only one copy of hello.
The output will be:
hello