1

What is the expected duration of a call to sleep with one as the argument? Is it some random time that doesn't exceed 1 second? Is it some random time that is at least one second?

Scenario:

  • Developer A writes code that performs some steps in sequence with an output device. The code is shipped and A leaves.

  • Developer B is advised from the field that steps j and k need a one-second interval between them. So he inserts a call to sleep(1) between those steps. The code is shipped and Developer B leaves.

  • Developer C wonders if the sleep(1) should be expected to sleep long enough, or whether a higher-resolution method should be used to make sure that at least 1000 milliseconds of delay occurs.

user229044
  • 232,980
  • 40
  • 330
  • 338
cardiff space man
  • 1,442
  • 14
  • 31

2 Answers2

2

sleep() only guarantees that the process will sleep for at least the amount of time specified, so as you put it "some random time that is at least one second."

Similar behavior is mentioned in the man page for nanosleep:

nanosleep() suspends the execution of the calling thread until either at least the time specified in *req has elapsed...

You might also find the answers in this question useful.

Community
  • 1
  • 1
Dan Fego
  • 13,644
  • 6
  • 48
  • 59
2

my man-page says this:

unsigned int sleep(unsigned int seconds);

DESCRIPTION
   sleep()  makes  the  calling  thread  sleep  until seconds seconds have
   elapsed or a signal arrives which is not ignored.
...
RETURN VALUE
   Zero if the requested time has elapsed, or the number of  seconds  left
   to sleep, if the call was interrupted by a signal handler.

so sleep makes the thread sleep, as long as you tell it, but a signals awakes it. I see no further guarantees.

if you need a better, more precise waiting time, then sleep is not good enough. There is nanosleep and (sound funny, but is true) select is the only posix portable way to sleep sub-second (or with higher precision), that I am aware of.

Jörg Beyer
  • 3,631
  • 21
  • 35
  • So if the return value is zero, it means that supposedly there are "no more" seconds to be slept. But if a signal terminated the sleep, and the thread had been asleep for 949 milliseconds, would sleep return 1 or 0? – cardiff space man Mar 08 '12 at 21:21
  • 1
    Although the difference is not relevant to this question, "makes the calling thread sleep" (the documentation) and "makes the process sleep" (your interpretation) are not the same thing. –  Mar 08 '12 at 21:39