C sleep function not working

对着背影说爱祢 提交于 2019-12-21 10:56:10

问题


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

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

int main()
{
        int i;
        printf("0 ");
        for(i = 1; i <20; ++i)
        {
            sleep(2);
            printf("%d ", i);
        }
        printf("\n");

        return 0;
}

The rest runs fine when sleep(2) is commented out, any ideas?


回答1:


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.




回答2:


hangs indefinitely implies that it's stuck or non-deterministic, and that doesn't happen. Your code works fine, after 38 seconds (19 *2) it dumps the string counting from 0 to 19. However I suspect this is what you were looking for it to do:

int main()
{
        int i;
        printf("0 ");
        fflush(stdout);  // Force the output to be printed
        for(i = 1; i <20; ++i)
        {
            sleep(2);
            printf("%d ", i);
            fflush(stdout); // Force the output to be printed
        }
        printf("\n");

        return 0;
}

the stdout stream is buffered and is only going to display when it hits a newline '\n' or if you want to view it "real time" as your call printf() you need to force it to flush the buffer one way or another. A call to fflush(stdout) will do this.




回答3:


Are you on a Windows computer? If so, include in your program, and to pause the program, write

Sleep(time_in_milliseconds)

where in your case time_in_milliseconds should be 2000.

On the other hand, if you're on a UNIX based computer, the code looks fine.



来源:https://stackoverflow.com/questions/13568388/c-sleep-function-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!