0

Its Saturday morning and thought to work on something good.And I am stuck up with a very small problem but for unknown reason.Please do make my morning cheerful by solving this.

I used sleep function in my program and used a printf statement before invoking sleep function to my surprise the program is sleeping before it invokes printf.Here is the code....

#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
int main(){
pid_t pt;
printf("ging to while loop");
printf("im sleeping");
sleep(1);
printf("im awoke");

}

Is my computer forsee my sleep function and sleeping before?

Another surprising thing i saw is using newline makes it sleep after invocation of first line.That is its working correctly.

Please explain me such weird behaviour?

Its sleeping before printf invocation.And then printing all the three results at a time.Please do help PS:LINUX(UBUNTU 14.04),GCC COMPILER

jack wilson
  • 145
  • 1
  • 13

1 Answers1

2

This is a simple thing. stdout is line buffer. When you are giving the \n then only will clear or flush the buffer, otherwise it will not clear. At the end of the program it will flush the all buffers. This is the reason you are getting the printf statement after the sleep.

So make your printf like this.

printf("ging to while loop\n");
printf("im sleeping\n");

Refer this link.

Karthikeyan.R.S
  • 3,991
  • 1
  • 19
  • 31
  • but what about printing them putting in a loop that works right ?is its way of outputing the content to stdout is unexpected or it is? – jack wilson Mar 14 '15 at 05:04
  • 1
    @jackwilson Please check out [this answer to an old question](http://stackoverflow.com/a/1716621/4067206). stdout is buffered and will only print when told to, or on a newline. There are ways to turn off this buffering if you want. Everything is explained in the link – Mario Mar 14 '15 at 05:05
  • No if you placed that into the while loop without giving the newline then it will not display the printf statement. As like above comment you can make your buffer disable. – Karthikeyan.R.S Mar 14 '15 at 05:09