C sleep function not working
Asked Answered
L

4

13

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?

Lilt answered 26/11, 2012 at 15:54 Comment(4)
Also note the line printf("0 ") doesn't run, so it's not an issue of time in sleep().Lilt
Buffering? What happens if you end your printed strings with a newline? Edit: works as expected for me, 38 seconds of silence, and then the numbers are printed.Gubernatorial
What happens if you do fflush(stdio); on every iteration?Equitation
possible duplicate of Why does printf not flush after the call unless a newline is in the format string?Teamwork
G
17

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.

Gatias answered 26/11, 2012 at 15:57 Comment(0)
T
6

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.

Teamwork answered 26/11, 2012 at 16:7 Comment(1)
@JamesJenkinson - :) It happens. Debuggers are nice for this so you can see it's doing something, lacking that, just wait the max time it can sleep()Teamwork
S
0

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>).

Syncretize answered 26/11, 2012 at 16:3 Comment(0)
T
-1

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.

Twittery answered 15/2, 2022 at 22:47 Comment(2)
Stack Overflow is mostly about asking and answering questions, so background information doesn't add much while cluttering content. Additionally, it seems like two users diagnosed the problem. The print function was buffered, causing the lack of output in the console. It wasn't a huge bug in Windows. I would recommend posting your very situation on Stack Overflow (concisely with minimal code to reproduce the problem) as something else than what you described is probably going on. You might be pleasantly surprised if someone diagnoses your problem to be something other than a bug in Windows.Gluttonize
This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From ReviewGluttonize

© 2022 - 2024 — McMap. All rights reserved.