LLVM API Documentation

Alarm.inc

Go to the documentation of this file.
00001 //===-- Alarm.inc - Implement Unix Alarm Support --------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the Reid Spencer and is distributed under the
00006 // University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the UNIX Alarm support.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include <signal.h>
00015 #include <unistd.h>
00016 #include <cassert>
00017 using namespace llvm;
00018 
00019 /// AlarmCancelled - This flag is set by the SIGINT signal handler if the
00020 /// user presses CTRL-C.
00021 static volatile bool AlarmCancelled = false;
00022 
00023 /// AlarmTriggered - This flag is set by the SIGALRM signal handler if the 
00024 /// alarm was triggered.
00025 static volatile bool AlarmTriggered = false;
00026 
00027 /// NestedSOI - Sanity check.  Alarms cannot be nested or run in parallel.  
00028 /// This ensures that they never do.
00029 static bool NestedSOI = false;
00030 
00031 static RETSIGTYPE SigIntHandler(int Sig) {
00032   AlarmCancelled = true;
00033   signal(SIGINT, SigIntHandler);
00034 }
00035 
00036 static RETSIGTYPE SigAlarmHandler(int Sig) {
00037   AlarmTriggered = true;
00038 }
00039 
00040 static void (*OldSigIntHandler) (int);
00041 
00042 void sys::SetupAlarm(unsigned seconds) {
00043   assert(!NestedSOI && "sys::SetupAlarm calls cannot be nested!");
00044   NestedSOI = true;
00045   AlarmCancelled = false;
00046   AlarmTriggered = false;
00047   ::signal(SIGALRM, SigAlarmHandler);
00048   OldSigIntHandler = ::signal(SIGINT, SigIntHandler);
00049   ::alarm(seconds);
00050 }
00051 
00052 void sys::TerminateAlarm() {
00053   assert(NestedSOI && "sys::TerminateAlarm called without sys::SetupAlarm!");
00054   ::alarm(0);
00055   ::signal(SIGALRM, SIG_DFL);
00056   ::signal(SIGINT, OldSigIntHandler);
00057   AlarmCancelled = false;
00058   AlarmTriggered = false;
00059   NestedSOI = false;
00060 }
00061 
00062 int sys::AlarmStatus() {
00063   if (AlarmCancelled)
00064     return -1;
00065   if (AlarmTriggered)
00066     return 1;
00067   return 0;
00068 }