[Previous]
[Contents]
[Next]

alarm()

schedule an alarm

Synopsis:

#include <unistd.h>

unsigned int alarm( unsigned int seconds );

Description:

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

Processor scheduling delays may cause the process not actually to begin handling the signal until 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, (unsigned)-1 is returned, and 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 <unistd.h>

int main( void )
  {
    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 re-arm: %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 do not have
     * a signal handler.
     */
    printf( "Hanging around, waiting to die\n" );
    pause();
    return (EXIT_SUCCESS);
  }

Classification:

POSIX 1003.1

Safety:
Interrupt handler No
Signal handler Yes, but modifies errno
Thread Yes

See also:

errno, pause(), sleep(), timer_create(), timer_gettime(), timer_settime()


[Previous]
[Contents]
[Next]