2

I thought I was doing something simple here, but C decided to go asynchronous on me. I'm not sure what's going on. Here's my code:

#include <stdio.h>
int main() {
    printf("start");
    sleep(5);
    printf("stop");
}

When I compile and run, I notice that sleep(5) works like a charm. But the compiler decided it was a good idea to skip the first printf() and go out of order, so when running, the program waits for 5 seconds and then prints startstop.

What's the deal? My theory is that the program initiates the print operation with the shell, then continues with the program, leaving Bash to wait until the program is no longer busy to actually render the strings. But I really don't know.

Thanks

ICoffeeConsumer
  • 812
  • 1
  • 8
  • 22
  • possible duplicate of [Why does printf not flush after the call unless a newline is in the format string?](http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin) – Charles Salvia Apr 24 '13 at 02:54
  • Possible duplicate of [Why does printf() not print anything before sleep()?](https://stackoverflow.com/questions/338273/why-does-printf-not-print-anything-before-sleep) – Faheel Jul 26 '17 at 22:37

3 Answers3

4

printf uses buffered output. This means that data first accumulates in a memory buffer before it is flushed to the output source, which in this case is stdout (which generally defaults to console output). Use fflush after your first printf statement to force it to flush the buffered data to the output source.

#include <stdio.h>
int main() {
    printf("start");
    fflush(stdout);
    sleep(5);
    printf("stop");
}


Also see Why does printf not flush after the call unless a newline is in the format string?

Community
  • 1
  • 1
Charles Salvia
  • 48,775
  • 12
  • 118
  • 138
  • Thanks! I should have known there would be more to it. At first I thought I had a rogue Python installation that was jealous of this C program rivaling its implementation in terms of syntactic brevity. – ICoffeeConsumer Apr 24 '13 at 02:58
2

Try adding '\n' to your printf statements, like so:

#include <stdio.h>
int main() {
    printf("start\n");
    sleep(5);
    printf("stop\n");
}

The compiler is not executing this out of order. Just the output is getting accumulated, and then displayed when the program exits. The '\n' will invoke the line discipline in the tty drivers to flush the output.

Ziffusion
  • 8,119
  • 3
  • 25
  • 50
0

Read this Q&A, it explains it.

Community
  • 1
  • 1
Toby
  • 286
  • 3
  • 8