2

I have a class that may be something like this:

class StreetSim{
  public:
  void operator(){
    //do cool things
    if(street_exploded) exit(5);
  }
};

This works great for a small program like this:

int main(){
  StreetSim ss;
  ss();
  return 0;
}

However now I want to embed this in another program. I would really like to not fork the process as a child, but I'm not allowed to change StreetSim. I would prefer something like this:

int main(){
  StreetSim ss;
  int k = catch(ss());
  if(k==5) 
    fprintf("the street exploded!");
  return k;
}

Is it at all possible to catch a program exit signal like this? I suspect not, but perhaps some gurus here might have some useful tribal knowledge about something like this.

Suedocode
  • 2,504
  • 3
  • 23
  • 41
  • 1
    StreetSim should throw an exception instead of `exit(5)`! It's a really bad idea to put `exit` in something like this. It hurts reusability. – Fred Larson Dec 05 '14 at 19:23
  • 3
    You *can* catch `exit` calls with [`std::atexit`](http://en.cppreference.com/w/cpp/utility/program/atexit), but there's nothing you can really do about the axtual "exiting", the program will still terminate. – Some programmer dude Dec 05 '14 at 19:23
  • 1
    elaborating on @Joachim's point: Trying to get around it with exceptions will just terminate the program anyway. Also, you would have UB if a `setjmp`/`longjmp` pair might omit calls to non-trivial dtor. – Deduplicator Dec 05 '14 at 19:27
  • I suggest return a status code from the `operator()` function. This will allow callers of the function to perform error handling without using the exception mechanism (or other complicated means like messing with the `exit` function). – Thomas Matthews Dec 05 '14 at 19:31
  • 2
    http://stackoverflow.com/questions/22843189/exit-call-inside-a-function-which-should-return-a-reference/22843464#22843464 – PaulMcKenzie Dec 05 '14 at 19:34
  • So that bit about not being able to change `StreetSim`... But this atexit call look like it has promise if it catches the exit *before* the memory and classes are destroyed. – Suedocode Dec 05 '14 at 19:41
  • Can you define very precisely what the restriction is on "change"? For example, can you modify an include file to contain `#define exit(x) throw(x)`? Can you link it in such a way that `exit` is hooked? – David Schwartz Dec 05 '14 at 19:58
  • The library is already compiled, but I *can* change the header files. Subverting the linker is an interesting idea, but I don't think that `#define` alone will do the trick. – Suedocode Dec 05 '14 at 21:59

0 Answers0