Add new api for basic signal handling for tools
[oota-llvm.git] / lib / Support / Signals.cpp
1 //===- Signals.cpp - Signal Handling support ------------------------------===//
2 //
3 // This file defines some helpful functions for dealing with the possibility of
4 // unix signals occuring while your program is running.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "Support/Signals.h"
9 #include <vector>
10 #include <algorithm>
11 #include <cstdlib>
12 #include <cstdio>
13 #include <signal.h>
14
15 static vector<string> FilesToRemove;
16
17 // IntSigs - Signals that may interrupt the program at any time.
18 static const int IntSigs[] = {
19   SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
20 };
21 static const int *IntSigsEnd = IntSigs + sizeof(IntSigs)/sizeof(IntSigs[0]);
22
23 // KillSigs - Signals that are synchronous with the program that will cause it
24 // to die.
25 static const int KillSigs[] = {
26   SIGILL, SIGTRAP, SIGABRT, SIGEMT, SIGFPE,
27   SIGBUS, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ
28 };
29 static const int *KillSigsEnd = KillSigs + sizeof(KillSigs)/sizeof(KillSigs[0]);
30
31
32 // SignalHandler - The signal handler that runs...
33 static void SignalHandler(int Sig) {
34   while (!FilesToRemove.empty()) {
35     std::remove(FilesToRemove.back().c_str());
36     FilesToRemove.pop_back();
37   }
38
39   if (find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd)
40     exit(1);   // If this is an interrupt signal, exit the program
41
42   // Otherwise if it is a fault (like SEGV) reissue the signal to die...
43 }
44
45 static void RegisterHandler(int Signal) { signal(Signal, SignalHandler); }
46
47 // RemoveFileOnSignal - The public API
48 void RemoveFileOnSignal(const string &Filename) {
49   FilesToRemove.push_back(Filename);
50
51   for_each(IntSigs, IntSigsEnd, RegisterHandler);
52   for_each(KillSigs, KillSigsEnd, RegisterHandler);
53 }