Karthick
Karthick

Reputation: 2882

Sleep and output flush

I saw the snippet below somewhere online. The following program doesnt print "hello-out". The reason I feel is because before it is actually flushed to the console from the buffer,

  #include <stdio.h>
  #include <unistd.h>
  int main()
  {
          while(1)
          {
                  fprintf(stdout,"hello-out");
                  fprintf(stderr,"hello-err");
                  sleep(1);
          }
          return 0;
  }

Is my reason correct? If not what is the correct reason?

Upvotes: 1

Views: 951

Answers (2)

sehe
sehe

Reputation: 392911

The reason the following fix is because I do know that stdout is line-buffered by default, whereas stderr is not.

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

int main()
{
    while(1)
    {
        fprintf(stdout,"hello-out");
        fflush(stdout);
        // sleep(1);
        fprintf(stderr,"hello-err");
        sleep(1);
    }
    return 0;
}

Update another way to 'fix' it without changing the source code is by using e.g. stdbuf:

 stdbuf -o 0 ./test

which switches standard output to unbuffer mode as well. Interestingly, if you specify

 stdbuf -e L ./test

to make stderr linebuffered as well, no output will appear at all (until the first lineend gets printed)

Upvotes: 1

littleadv
littleadv

Reputation: 20272

You should put \n at the end of the string to have it flushed, or use fflush to force it out.

Upvotes: 2

Related Questions