This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: c++ exceptions and signals



> If I write a signalhandler and throw an exception there I don't manage to
> catch this exception in the main program.

Don't do that!  It's not safe to throw C++ exceptions from signal handlers.

The problem is that the point where the exception might be thrown is too
unconstrained, especially for a signal that comes from elsewhere, like
SIGTERM.  It might happen at a point where a stack frame is
only partly formed, for example.  Even if you didn't have that problem,
in code like

	char* foo = 0;
	foo = new char[SIZE];

it might happen either after the call to new but before the assignment to
foo, so you have no way of avoiding memory leaks.

> Do you know whats going wrong? Or how to make a signal throw an
> exception and catch it?

Das ist leider verboten!

The closest you can come is to have your signal handler set a flag
(declared as volatile), and other code can then poll that flag,
throwing an exception if the flag becomes true.


> Thanks a lot
> 
> The small program i tried:
> #include <iostream.h>
> #include <stdexcept>
> #include <signal.h>
> 
> 
> class Peter : public exception
> {
> public:
>   virtual const char* what () const { return "Peters Ausnahme"; } 
> };
> 
> 
> void termhandler(int n) 
> { 
>   signal(SIGTERM, termhandler ); 
>   cout << "Hier ist der Signalhandler"<<endl; 
>   throw exception();
> }
> 
> 
> 
> main()
>   try
>     {
>       cout << "Signal: " << signal(SIGTERM, termhandler ) << endl;
>       while(true)
> 	sleep(15);
>     }
>   catch(exception& ex)
>     {
>       cout << "Caught exception : "; 
>       cout << ex.what() << endl;
>       //throw;
>     }
>   catch(...)
>     {
>       cout << "Dies sollte alle exceptions abfangen." << endl;
>       throw;
>     }
> 
> 
> 
> Peter Maunz
> University of Konstanz
> Faculty of Physics
> AG Prof Rempe
> +49 7531 88-3838
> 
> Peter.Maunz@uni-konstanz.de
> 


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]