abhi
abhi

Reputation: 3586

Different Behavior of a code using fork when run on terminal & when o/p redirected to a file

I came across some test code which is giving different output when executed on terminal directly and when its output is redirected to a file:

# include <stdio.h>
# include <stdlib.h>
int main()
{
     printf("hello\n");
     if(fork() ==0)
     {
            printf("world\n");
     }
}

On the terminal the output is:

abhi@ubuntu:~/Desktop/ad/A1/CC$ ./vb
hello
abhi@ubuntu:~/Desktop/ad/A1/CC$ world

(The cursor is still blinking after printing world & normal prompt is shown after enter is pressed.)

On redirecting output to a file:

./vb >v.txt
 abhi@ubuntu:~/Desktop/ad/A1/CC$ cat v.txt 
 hello
 hello
 world

As far as I understand the parent is not waiting for child it prints hello & returns. The child then should print world and the code should terminate.

What I am not able to understand is why the code is behaving differently when its output is redirected. What is the cause of this?

Upvotes: 1

Views: 145

Answers (1)

cnicutar
cnicutar

Reputation: 182734

When stdout is redirected to a file, it's not line buffered. When it's a tty, it is. So when writing to a tty the printf immediately writes to stdout and "that's all she wrote".

But when stdout is redirected to a file "hello\n" remains in the stdio buffer. When you fork, both processes (both the child and the parent) end up with a copy of the stdio buffers, which they flush at exit.


Off-topic: in my opinion o/p is a really really bad way to write "output" - I hate it with the white-hot intensity of a thousand suns.

Upvotes: 8

Related Questions