-3

I created simple code to test the sleep() function. in C.

I execute the following code in attempts that the program waits 5 seconds before terminating:

#include <stdlib.h>
#include <stdio.h>

int main(){
    int n=0;
    for (n=1;n<=10;n++){
        sleep(.5);
    }
    return 0;
}

It however waits about say 100ms. Well, definitely less than one second.

Now if I instead executed the following code:

#include <stdlib.h>
#include <stdio.h>

int main(){
    int n=0;
    for (n=1;n<=10;n++){
        sleep(1);
    }
    return 0;
}

The program behaves as expected (waits 10 seconds before exiting).

Why does sleep() fail to execute properly when the parameter is a float?

and what's the absolute best function that's compatible with all systems that I can use in place of sleep?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Mike -- No longer here
  • 2,064
  • 1
  • 15
  • 37
  • I'm surprised that a 1k user shows so little research. A quick look at the documentation would have shown you that `sleep` takes an integer as argument. It's also very easy to find the answer to your second question here on SO. – klutt Jun 30 '18 at 00:42
  • Possible duplicate of [Is there an alternative sleep function in C to milliseconds?](https://stackoverflow.com/questions/1157209/is-there-an-alternative-sleep-function-in-c-to-milliseconds) – klutt Jun 30 '18 at 00:43
  • Also, please read tag descriptions. The debugging tag is completely unsuitable for this question. – klutt Jun 30 '18 at 00:44
  • 1
    Did you not get a warning about an implicit declaration of `sleep`? – Keith Thompson Jun 30 '18 at 00:44
  • Please don't think that http://idownvotedbecau.se/noresearch/ , but it could be a reason for the downvotes. – Yunnosch Jun 30 '18 at 06:09

1 Answers1

11

Type man 3 sleep and read it.

sleep requires an unsigned int argument. It can only sleep for a whole number of seconds.

If you pass it an argument of a different numeric type, it's implicitly converted to unsigned int. Converting a floating-point value to an integer type truncates.

That's assuming that the declaration for the sleep function is visible. In your program, you don't have the required #include <unistd.h>. In C99 or later, calling a function with no visible declaration is illegal. In C90, the compiler will make certain assumptions about the function. In this case, your program's behavior is undefined.

So sleep(.5) is equivalent to sleep(0).

Search your system's documentation for usleep (microseconds) or nanosleep (nanoseconds).

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631