the unexpected output of fork() when redirected to file.txt

245 views Asked by At

I am working on process control in linux operating system using c. the fork() function really confuse me . what I know : when fork() is called
1) whatever the code just after fork() , is copied to the child process. 2) we can not determine which (parent or child) will run first. I run the following code.

int main() {
    printf("Hi");
    fork();
    return 0;
}

my first question is: why I get Hi two times? it is explained in Working of fork() in linux gcc , but still I want someone to explain with more simplicity.

my second doubt: when I redirect my output to somefile.txt even if I use newline character (\n) the output is:

hi

hi

please explain ...

please provide me some detail if I missed , in understanding the fork()

2

There are 2 answers

1
md5 On

why I get Hi two times ?

If you write:

#include <stdio.h>

int main()
{
  printf("Hi");

  for (;;)
    ;

  return 0;
}

"Hi" won't be printed on stdout, since the standard ouput stream is line-buffered by default. This means that you have to add a '\n' to flush this buffer.

#include <stdio.h>

int main()
{
  printf("Hi\n");

  for (;;)
    ;

  return 0;
}

With fork, the father process' buffers will be copied into the child process.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
  printf("Hi");

  /* stdout in the father process contains "Hi" */
  fork();

  /* stdout in the father process contains "Hi" */
  /* stdout in the child process contains "Hi" */

  /* With return statement all buffers are flushed and "Hi" is printed twice */
  return 0;
}
0
Lidong Guo On

There are there kind of buffers:

Full buffer

Line buffer

No buffer

When you use printf in terminal .It is line buffer default . So you can use \n to flush the buffer. After flush the buffer, you print only one hi

When you use printf redirect to a file .It is full buffer default . So you can not use \n to flush the buffer. Without flush the buffer, you print two hi

You can use setvbuf`to change the buffer type.