blob: 503d3a63b29886168c365ca666c073e2cf7ffd15 [file] [log] [blame]
Chris Lattnerbac27a42002-04-18 19:53:53 +00001//===- 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
Chris Lattner01e770a2003-05-22 21:59:35 +000015static std::vector<std::string> FilesToRemove;
Chris Lattnerbac27a42002-04-18 19:53:53 +000016
17// IntSigs - Signals that may interrupt the program at any time.
18static const int IntSigs[] = {
19 SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
20};
21static 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.
25static const int KillSigs[] = {
Chris Lattner7c97cee2002-09-13 14:57:24 +000026 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ
27#ifdef SIGEMT
28 , SIGEMT
29#endif
Chris Lattnerbac27a42002-04-18 19:53:53 +000030};
31static const int *KillSigsEnd = KillSigs + sizeof(KillSigs)/sizeof(KillSigs[0]);
32
33
34// SignalHandler - The signal handler that runs...
35static void SignalHandler(int Sig) {
36 while (!FilesToRemove.empty()) {
37 std::remove(FilesToRemove.back().c_str());
38 FilesToRemove.pop_back();
39 }
40
Anand Shuklacfb22d32002-06-25 20:55:50 +000041 if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd)
Chris Lattnerbac27a42002-04-18 19:53:53 +000042 exit(1); // If this is an interrupt signal, exit the program
43
44 // Otherwise if it is a fault (like SEGV) reissue the signal to die...
Chris Lattner39602b22003-05-27 16:25:04 +000045 signal(Sig, SIG_DFL);
Chris Lattnerbac27a42002-04-18 19:53:53 +000046}
47
48static void RegisterHandler(int Signal) { signal(Signal, SignalHandler); }
49
50// RemoveFileOnSignal - The public API
Chris Lattner01e770a2003-05-22 21:59:35 +000051void RemoveFileOnSignal(const std::string &Filename) {
Chris Lattnerbac27a42002-04-18 19:53:53 +000052 FilesToRemove.push_back(Filename);
53
Anand Shuklacfb22d32002-06-25 20:55:50 +000054 std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
55 std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
Chris Lattnerbac27a42002-04-18 19:53:53 +000056}