alarm() — Set an alarm

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 alarm(unsigned int seconds);

General description

Generates a SIGALRM signal after the number of seconds specified by the seconds parameter has elapsed. The SIGALRM signal delivery is directed at the calling thread.

seconds is the number of real seconds to wait before the SIGALRM signal is generated. Because of processor delays, the SIGALRM signal may be generated slightly later than this specified time. If seconds is zero, any previously set alarm request is canceled.

Only one such alarm can be active at a time. If you set a new alarm time, any previous alarm is canceled.

This function is supported only in a POSIX program.

Special behavior for XPG4: The fork() function clears pending alarms in the child thread. However, a new thread image created by one of the exec functions inherits the time left to an alarm in the old thread's image.

Special behavior for XPG4.2: alarm() will interact with the setitimer() function when the setitimer() function is used to set the ‘real’ interval timer (ITIMER_REAL).

alarm() does not interact with the usleep() function.

Returned value

If a prior alarm request has not yet completed, alarm() returns the number of seconds remaining until that request would have generated a SIGALRM signal.

If there are no prior alarm requests with time remaining, alarm() returns 0. Because alarm() is always successful, there is no failure return. If any failures are encountered that prevent alarm() from completing successfully, an abend is generated.

Example

CELEBA05
⁄* CELEBA05

   The following example generates a SIGALRM signal.

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

volatile int footprint=0;

void catcher(int signum) {
  puts("inside signal catcher!");
  footprint = 1;
}

main() {
  struct sigaction sact;
  volatile double count;
  time_t t;

  sigemptyset(&sact.sa_mask);
  sact.sa_flags = 0;
  sact.sa_handler = catcher;
  sigaction(SIGALRM, &sact, NULL);

  alarm(5); ⁄* timer will pop in five seconds *⁄

  time(&t);
  printf("before loop, time is %s", ctime(&t));
  for (count=0; (count<1e10) && (footprint == 0); count++);
  time(&t);
  printf("after loop, time is %s", ctime(&t));

  printf("the sum so far is %.0f\n", count);

  if (footprint == 0)
    puts("the signal catcher never gained control");
  else
    puts("the signal catcher gained control");
}
Output
before loop, time is Fri Jun 16 08:37:03 2001
inside signal catcher!
after loop, time is Fri Jun 16 08:37:08 2001
the sum so far is 17417558

Related information