'C sleep function not working

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?



Solution 1:[1]

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.

Solution 2:[2]

Are you on a Windows computer? If so, include <windows.h> 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 (no need for <windows.h>).

Solution 3:[3]

I came across your question when researching a problem I have on Windows.

I have a command line program that has 2 threads, one for reading data, and the other for writing it (in a queue).

Every 30 seconds the reader (the initial process) writes out a progress message and was appearing to hang, so I hit Ctrl-C once and found out that my program was actually continuing (Ctrl-C once did not kill it).

Anyway, while try to work out what was going on, I started another console window and ran the command:

for /l %g in () do @(dir & timeout /t 2)

Every once in a while it would lock up too, and a Ctrl-C would free it up.

There appears to be some sort of bug in Windows where when the system is otherwise really busy the Sleep function does not return (Ctrl-C seems to unlock it).

Anyway, hope that helps someone.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 TBG
Solution 3 gazillabyte