[Previous] [Contents] [Next]

alarm()

Schedule an alarm

Synopsis:

#include <unistd.h>

unsigned int alarm( unsigned int seconds );

Library:

libc

Description:

The alarm() function causes the system to send the calling process a SIGALRM signal after a specified number of realtime seconds have elapsed.

Processor scheduling delays may cause the process to handle the signal after the desired time.

The alarm() requests aren't stacked; only a single SIGALRM generation may be scheduled in this manner. If the SIGALRM hasn't yet been generated, the alarm() reschedules the time at which the SIGALRM is generated.

If seconds is zero, any previous alarm() request is canceled.

Returns:

The number of seconds before the calling process is scheduled to receive a SIGALRM from the system, or zero if there was no previous alarm() request.

If an error occurs, an (unsigned)-1 is returned (errno is set).

Errors:

EAGAIN
All timers are in use. You'll have to wait for a process to release one.

Examples:

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

int main()
  {
    unsigned int  timeleft;

    printf( "Set the alarm and sleep\n" );
    alarm( 10 );
    sleep( 5 );   /* go to sleep for 5 seconds */

    /*
     * To get the time left before the SIGALRM is 
     * to arrive, one must cancel the initial timer, 
     * which returns the amount of time it had 
     * remaining.
     */
    timeleft = alarm( 0 );
    printf( "Time left before cancel, and rearm: %d\n",
        timeleft );

    /*
     * Start a new timer that kicks us when timeleft
     * seconds have passed.
     */

    alarm( timeleft );

    /*
     * Wait until we receive the SIGALRM signal; any
     * signal kills us, though, since we don't have
     * a signal handler.
     */
    printf( "Hanging around, waiting to die\n" );
    pause();
    return EXIT_SUCCESS;
  }

Classification:

POSIX 1003.1

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

Caveats:

Requests from alarm(), TimerAlarm(), and ualarm() aren't "stacked;" only a single SIGALRM generator can be scheduled with these functions. If the SIGALRM signal hasn't been generated, the next call to alarm(), TimerAlarm(), or ualarm() reschedules it.

See also:

errno, pause(), sleep(), TimerAlarm(), timer_create(), timer_delete(), timer_gettime(), timer_settime(), ualarm()


[Previous] [Contents] [Next]