D exit() function?

Daniel Keep daniel.keep.lists at gmail.com
Sun Mar 25 15:32:48 PDT 2007



Jarrett Billingsley wrote:
> "Krzysztof Szukielojc" <krzysztof.szukielojc at gmail.com> wrote in message 
> news:eu6m78$m1r$1 at digitalmars.com...
> 
>> I think simple scope(exit) should do the trick.
>>
>> void exitFun(){
>> ...
>> }
>>
>> void main(){
>>   scope(exit) exitFun();
>>   ...
>> }
>>
> 
> No, I'm not looking for an atexit() replacement, sorry.  I'm looking for a 
> way to end my D program at an arbitrarily deep call depth and still have it 
> call the RTL cleanup functions.
> 
> I suppose it would be possible to do something like:
> 
> extern(C) void _cleanupD()
> {
>     _moduleDtor();
>     gc_term();
> }
> 
> ...
> 
> void main()
> {
>     atexit(&_cleanupD);
> 
>     // program
> }
> 
> But that's horribly non-portable.
> 
> Something like this should be in Phobos. 

Another way of doing it, stolen from Python :P

> class SystemExit : Object {}
>
> int main(char[][] args)
> {
>     int result = 0;
>     try
>     {
>         result = appmain(args);
>     }
>     catch( SystemExit e )
>     {
>         // Meh.
>     }
>     return result;
> }
>
> int appmain(char[][] args)
> {
>     // Your code here!
> }
>
> // ...
>
> void really_deep_function()
> {
>     throw new SystemExit;
> }

This should be portable, and ensures that all dtors (class and module)
and scope(exit)/scope(failure) get executed.  It might take a little
longer to get back up to main, but at least it should be safe :)

	-- Daniel

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/


More information about the Digitalmars-d-learn mailing list