4

I am trying to understand fork() using some test program. And I find different behaviors between cout and printf() :

program 1:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
using namespace std;

int main()
{
    printf("Hi , %d\n" , getpid());
    fork();
    return 0;
}

I get:

Hi , 9375

Hi , 9375

program 2:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
using namespace std;

int main()
{
    cout << "Hi , " <<getpid() << endl;
    fork();
    return 0;
}

I get:

Hi , 7277

The only difference between two program is the first use printf() to print the output while second use cout

Can anyone explain it? Thanks

chenglg
  • 53
  • 3
  • `cout = c++` , `printf = c`. You can use at c++ with both of them, but it is always advise to use the native language display functions. – Orel Eraki Jan 31 '14 at 23:18
  • 1
    I only get one output in the first one. Were you writing to a file instead of the terminal? – Barmar Jan 31 '14 at 23:19
  • 2
    possible duplicate of [Understanding of Fork in C](http://stackoverflow.com/questions/21349944/understanding-of-fork-in-c) – kuroi neko Jan 31 '14 at 23:20
  • @OrelEraki My question is when using printf , output "Hi , 9375" is printed out twice while using cout out put "Hi , 7277" is printed only once – chenglg Jan 31 '14 at 23:21

1 Answers1

13

When you use stdio, stdout is fully-buffered unless it's writing to a terminal; when writing to a terminal it's line-buffered.

So if you run Program 1 with output redirected to a file or pipe, printf writes the line to the output buffer, but doesn't flush the buffer. When the process forks, the buffer is duplicated in both processes. When they exit, they each flush their copy of the buffer, which prints the line.

You would get the same result in Program 2 if you'd written:

cout << "Hi , " <<getpid() << "\n";

But endl, in addition to outputting the newline character, also flushes the buffer. The equivalent in Program 1 would be:

printf("Hi , %d\n" , getpid());
fflush(stdout);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I think you're right, Barmar, and by constrast, cout << endl always flushes the buffer regardless of whether it's going to a terminal or not. – Klitos Kyriacou Jan 31 '14 at 23:27
  • std::endl is more than "\n", it is equivalent to call fflush() after printf – Joky Jan 31 '14 at 23:30
  • 1
    That's what I said. If you changed `endl` to `"\n"` Program 2 would be like Program 1, because it wouldn't flush the buffer. – Barmar Jan 31 '14 at 23:32