Alon
Alon

Reputation: 464

The sleep command executes not how i expected

int main()
{
  printf("Whats up");
  sleep(3);
  printf("StackOverflow? All having a nice day? ");
}

Why is the output after 3 seconds "Whats up Stack.." and not first "Whats up" and then, 3 sec later the rest?

Upvotes: 1

Views: 105

Answers (1)

P.P
P.P

Reputation: 121387

It's because stdout is usually line-buffered. So your C library buffers the output. You can flush this by using \n in printf() or by calling fflush(stdout).

  printf("Whats up\n");

or

fflush(stdout); // call after the printf

You can also turn off the buffering with setbuf():

setbuf(stdout, 0);

Upvotes: 8

Related Questions