[m-users.] Calling exit(3) from a foreign predicate

Volker Wysk post at volker-wysk.de
Thu Jul 20 21:11:17 AEST 2023


Am Donnerstag, dem 20.07.2023 um 20:31 +1000 schrieb Julien Fischer:
> On Thu, 20 Jul 2023, Volker Wysk wrote:
> 
> > Just a short question:
> > 
> > May a foreign predicate call the exit(3) function?
> 
> A foreign predicate can do that, there's nothing the Mercury compiler
> can do to stop it.

I mean, is it allowed to?

> > Or does Mercury need a proper shutdown?
> 
> Calling exit() directly will bypass the usual shutdown of the Mercury
> runtime. Among the effects of that will be:
> 
> - Finalizers will not be run.
> - The Mercury exit status will not be returned to the OS.
> 
> If for some reason, you do want to call exit() from a foreign predicate,
> I would suggest something like the following:
> 
>       exit(mercury_runtime_terminate());
> 
> (mercury_runtime_terminate() is declared in runtime/mercury_wrapper.h)
> 
> The only time I've wanted to something similar was from within the
> event loop of the old GLUT library, where there that library provided
> no way of getting out of the event loop. (See the quit/2 predicate
> in extras/graphics/mercury_glut/glut.m.)
> 
> In general, given the choice, I would simply throw an exception that is
> caught be a top-level exception handler in main/2 and exit (normally)
> that way.

That's how I did it until now. 

This leads me to a simple idea. What about introducing some type 

:- type shutdown ---> shutdown(int).

in io.m, and a predicate

:- pred exit(int::in) is erroneous.

exit(ExitCode) :-
    throw(shutdown(ExitCode)).


The Mercury runtime would catch shutdown/1 exceptions and exit with the
supplied exit code. After doing all shutdown and cleanup. The program would
still be able to catch such shutdown/1 exceptions, if that is desired.

Cheers,
Volker
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: This is a digitally signed message part
URL: <http://lists.mercurylang.org/archives/users/attachments/20230720/8cf2809e/attachment.sig>


More information about the users mailing list