C sleep function not working

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

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

#include 
#include 

int main()
{         


        
3条回答
  •  萌比男神i
    2021-01-04 20:28

    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.

提交回复
热议问题