0

I wrote the following piece of code to simulate a callback. But this got stuck and not even prints "inside main". I tried this on my unix machine and also on online compiler but same behavior. Have I missed anything ?

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

void sleep_50sec()
{
    printf("inside sleep_50sec");

    sleep(50);

}

int main()
{
    int i;
    printf("inside main");
    sleep(1);

    for( i =0; i < 100;i++)
    {   printf("Loop %d",i);
        sleep_50sec();
    }
return 0;
}

Output

root@xyz> ./a.out
Vinay Shukla
  • 1,751
  • 9
  • 34

3 Answers3

3

Add \n when printing to stdout.

printf("inside main\n");

The reason a \n is needed is because printf flushes data to stdout after \n was reached.

You can print to stderr to see your data immediately, without using \n:

fprintf(stderr, "test");

By the way, when calling printf() output will be written to stdout. So printf(...) is the same as fprintf(stdout, ...)

arminb
  • 1,788
  • 3
  • 21
  • 38
1

You have to flush the stdout. It can be done by the '\n' character inside the format string or by the fflush command:

void sleep_50sec() {
    printf("inside sleep_50sec");
    fflush(stdout);
    sleep(50);
}
Akira
  • 4,100
  • 3
  • 20
  • 39
0

The reason you're not seeing anything printed is because the crt (C runtime) buffers your outputs and will only output to the screen after K characters have been accumulated. One solution will be to use '\n' - this hints crt that a complete line has been written, and that it should print it to the screen. Another solution will be to implicitly flush stdout like in my example below:

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

void sleep_50sec()
{
    printf("inside sleep_50sec");
    fflush(stdout);

    sleep(50);

}

int main()
{
    int i;
    printf("inside main");
    fflush(stdout);
    sleep(1);

    for( i =0; i < 100;i++)
    {   printf("Loop %d",i);
        fflush(stdout);
        sleep_50sec();
    }
return 0;
}
Ishay Peled
  • 2,600
  • 1
  • 19
  • 34