mathieu said:
I am trying to reuse a piece of code that was designed as an
application. The code is covered with 'exit' calls. I would like to
reuse it as a library. For that I renamed the 'main' function into
'mymain', but I am stuck as to what I should do for the 'exit'.
AFAIK there is no portable way to catch the exit. The only thing I
can think of is atexit, but that does not work since 'exit' is still
called afterward.
What I am thinking now is that I need to replace all exit(val) with
longjmp(env, val). And make 'env' global.
The real problem, I presume, is that you have exit calls from
functions other than main(). In the original version of the program,
each such call terminates the main program; in your bigger program
with main renamed to mymain, you want to terminate mymain, not your
new main. Right?
Keeping it as a separate program and invoking it with system() might
be your best bet. The behavior of system() is largely
implementation-defined, particularly its return value, but if you're
only targeting a limited number of systems you can deal with that with
a few #ifdef's.
If you want the resulting code to be portable to all conforming
systems, things are a bit more difficult. On any one system, you
should be able to tell from the result returned by system() whether
the invoked program did an exit(EXIT_SUCCESS) or an exit(EXIT_FAILURE)
(or some other system-specific value), but there's no portable way to
do that.
You'll also need to take some care to ensure that
system("existing_program") actually invokes what you want it to
invoke. The details are system-specific, but at least for Unix-like
and Windows-like systems, think about PATH settings.
<OT>
Here's another possibility. I happen to know that there's another
language, whose name is that of our local favorite language with a
couple of plus signs appended to it, which supports the kind of
control flow you're looking for. Rather than calling exit, you can
"throw" an "exception" and "catch" it at whatever level you like
rather than letting it propagate out and terminate the program. It's
not inconceivable that you could recompile this program using a
compiler for this Other Language and make use of the OL's features.
This approach could be fraught (fraught, I say!) with peril. There
are subtle differences between C and the OL, some of which may prevent
valid C code from compiling, and some of which may silently change its
behavior. And if you take that approach, we can't help you here, but
the folks over in comp.lang.thatotherlanguage or
comp.lang.thatotherlanguage.moderated will be glad to do so.
</OT>
But still, I think that system() is your best bet, requiring no
changes to the program and (probably) just a little bit of
system-specific scaffolding.