1

I have a file named test.c (Its contents are given below)

#include <stdio.h>
#include <unistd.h>

int main()
{
    printf("T\n");
    fork();
    printf("F\n");
}

The expected result is:

T
F
F

Compiling with gcc and executing ./a.out ,the output is:

T
F
F

which matches the expected answer.

But ambiguity arises when I redirect the output to another file.

$ ./a.out > Output.txt 

The Output.txt has the following data:

T
F
T
F

Why is there an additional T in my Output.txt file when I use redirectors?

1) I've check this in multiple PC's running on ubuntu with gcc installed.

2) Tried deleting the Output.txt and moving all the files to a different location, but this still persists.

P.s. this works fine without the redirector.

kalpaj agrawalla
  • 878
  • 1
  • 9
  • 19

1 Answers1

2

I think it's because of the buffer, give a try with the follow code:

#include <stdio.h>
#include <unistd.h>

int main() {
    printf("T\n");
    fflush(stdout);
    fork();
    printf("F\n");
}
Esdras Xavier
  • 867
  • 1
  • 7
  • 18