C sleep function not working

前端 未结 3 1542
执念已碎
执念已碎 2021-01-04 20:22

When including the sleep function from unistd.h the program hangs indefinitely:

#include 
#include 

int main()
{         


        
3条回答
  •  醉梦人生
    2021-01-04 20:28

    There's nothing wrong with the code, but note that in many cases the output of printf is buffered, meaning that the output appears on the console only if you explicitly call fflush(stdout), you print a newline, or the buffer becomes full. Since you don't print a newline until the very end, you will see nothing in the for loop for 40 seconds (because the stuff that printf printed is still in the buffer). Then, when the execution hits printf("\n"), everything will be printed at once as the buffer is flushed.

    So, the bottom line is: either call fflush(stdout) before you call sleep to ensure that nothing stays in the output buffer, or wait for 40 seconds and you will get the output in a single batch in the end.

提交回复
热议问题