Problem with execution of fork system call if i use \n

hi all,

i tried the following source codes:
fork1.c:

main()
{
  printf("demo of fork\n");
  fork();
  printf("hello");
}

output:

demo of fork
hello hello

fork2.c:

main()
{
  printf("demo of fork");
  fork();
  printf("hello");
}

output(fork2.c):

demo of fork
hello hello demo of fork

In both the programs chilld and parent process are supposed to execute the statement(here its printf("hello")) which is next to fork call.But why the printf("demo of fork") is getting executed twice.Pls clarify my doubt.

Thanks in advance.

It is because printf is "buffered," meaning printf will group the output of a process together. While buffering the output for the parent process, the child may also use printf to print out some information, which will also be buffered. As a result, since the output will not be send to screen immediately, you may not get the right order of the expected result. Worse, the output from the two processes may be mixed in strange ways.
To overcome this problem, we should use newline at the end of each printf as newline causes buffer flush.
OR we may consider to use the "unbuffered" write.
Prototype: int write(int fd, char *Buff, int NumBytes);

1 Like

What happens is this:

// Without \n, this goes into a buffer and isn't printed yet.
printf("demo of fork");
// This creates a precise duplicate of the process -- including buffers.
// "demo of fork" will now be printed twice!
fork();
// this adds more stuff to the buffers of both programs.
printf("hello");
// The buffers will be flushed when the programs exit.  They may not exit
// in any particular order, and may try and print at the same time,
// causing the garble you see.
printf("demo of fork");
// Force it to print the buffer NOW, without waiting, so the child process
// doesn't get a copy of it in its own buffer.
fflush(stdout);
fork();
printf("hello");
1 Like

Thanks a lot anurag.

---------- Post updated at 07:02 AM ---------- Previous update was at 07:01 AM ----------

Thanks a lot corona.