Domanda

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

È stato utile?

Soluzione

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top