views:

21

answers:

1

I am writing code that needs to compile and run without error on both Unix/Mac (with GCC) and on Win32 (with mingw). The code has to run in a wide variety of different environments and it has loadable modules that I can't control, so I typically protect each module with a setjmp() and signal().

I see that WIN32 has both setjmp() and signal(). Will the code work portably, or do I need to worry?

+2  A: 

Go ahead and worry. The CRT should emulate signal() but the MSVC one explicitly mentions that longjmp() is not legal in a handler unless it handles SIGFPE. Check yours.

The equivalent of SIGSEGV is an SEH exception with exception code 0xc0000005 (STATUS_ACCESS_VIOLATION). The MSVC compiler allow catching them with the __try and __except keywords.

The idea of "protecting" a module like this is deeply flawed. Your program's state is corrupted beyond repair, you have no idea how it was mutated so you have no chance to restore it. Continuing to run can cause a number of mishaps. You'll be lucky when it dies on another exception, giving you no clue what the real problem was, but it is more likely to just generate bad data that won't be diagnosed for a long time. You are much better off just not writing code like this. And solve your porting problem in the process.

Hans Passant
Thanks for the message. I'll try using __try and __except. I was using a try and catch (from C++), but it didn't do the magic that I wanted.
vy32
As an added comment, normally the problems we encounter are not write errors, they are read errors, and they are most frequently caused because a decoder is trusting a pointer value that shouldn't be. I know that this approach is deeply flawed, but it is, unfortunately, better than the alternative.
vy32
Followup -- __try and __except don't work under mingw, but SIGSEGV is caught on mingw with signal().
vy32