usleep()

Updated: May 06, 2022

Suspend a thread for a given number of microseconds

Synopsis:

#include <unistd.h>

int usleep( useconds_t useconds );

Arguments:

useconds
The number of microseconds that you want to process to sleep for. This must be less than 1,000,000.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The usleep() function suspends the calling thread until useconds microseconds of realtime have elapsed, or until a signal that isn't ignored is received. The time spent suspended could be longer than the requested amount due to the nature of time measurement (see the Understanding the Microkernel's Concept of Time chapter of the QNX Neutrino Programmer's Guide), or due to the scheduling of other, higher-priority threads.

If useconds is 0, usleep() has no effect.

Note: While usleep() looks like you can specify a sleep duration down to the microsecond level, the actual delay will still be driven by the system clock tick. Assuming the usual default clock tick is 1 ms, the shortest delay you can get from usleep() will be 1.5 ms on average.

Returns:

0
Success.
-1
An error occurred (errno is set).

Errors:

EAGAIN
No timer resources are available to satisfy the request.
EINTR
The call was interrupted by a signal.
EINVAL
The useconds argument is too large.

Examples:

/*
 * The following program sleeps for the
 * number of microseconds specified in argv[1].
 */
#include <stdlib.h>
#include <unistd.h>

int main( int argc, char **argv )
{
    useconds_t microseconds;

    microseconds = (useconds_t)strtol( argv[1], NULL, 0 );
    if( usleep( microseconds ) == 0 ) {
        return EXIT_SUCCESS;
    }
    
    return EXIT_FAILURE;
}

Classification:

Standard Unix; removed from POSIX.1-2008

Safety:  
Cancellation point Yes
Interrupt handler No
Signal handler Yes
Thread Yes