sleep() — Suspend execution of a thread

Standards

Standards / Extensions C or C++ Dependencies

POSIX.1
XPG4
XPG4.2
Single UNIX Specification, Version 3

both

POSIX(ON)

Format

#define _POSIX_SOURCE
#include <unistd.h>

unsigned int sleep(unsigned int seconds);

General description

Suspends thread execution for a specified number of seconds. Because of processor delays, the thread can sleep slightly longer than this specified time. An unblocked signal received during this time (for which the action is to invoke a signal handler function or to end the thread) “wakes up” the thread prematurely. When that function returns, sleep() returns immediately even if there is sleep time remaining.

This function is supported only in a POSIX program.

Returned value

If the thread slept for the full specified time, sleep() returns 0.

If the thread awoke prematurely because of a signal whose action is to invoke a signal-handling function or to end the thread, sleep() returns the number of seconds remaining in its sleep time (that is, the value of seconds minus the actual number of seconds that the thread was suspended).

sleep() always succeeds, so there is no failure return. An abend is generated when any failures are encountered that prevent this function from completing successfully.

There are no documented errno values.

Example

CELEBS29
⁄* CELEBS29

   This example suspends execution for a specified time.

 *⁄
#define _POSIX_SOURCE
#include <stdio.h>
#include <time.h>
#include <unistd.h>

main() {
  unsigned int ret;
  time_t t;
  time(&t);
  printf("starting sleep at %s", ctime(&t));
  ret = sleep(10);
  time(&t);
  printf("naptime over at %s", ctime(&t));
  printf("sleep() returned %d\n", ret);
}
Output
starting sleep at Fri Jun 16 07:44:47 2001
naptime over at Fri Jun 16 07:44:58 2001
sleep() returned 0

Related information