Exit in Lisp
Here’s an idiomatic Lisp example demonstrating the concept of exiting a program:
This Lisp program demonstrates how to exit a program with a specific status code. Let’s break it down:
We define a
main
function to encapsulate our program logic.Inside
main
, we useunwind-protect
, which is similar totry-finally
in other languages. It ensures that cleanup code is executed even if an unwind (like an exit) occurs.The
progn
form groups multiple expressions together.We use
format
to print a message to the console before exiting.sb-ext:exit
is used to exit the program with a specific status code. This is implementation-specific (for SBCL), as Common Lisp doesn’t have a standard way to exit with a status code.The cleanup code inside
unwind-protect
won’t be executed due to the immediate exit.Finally, we call the
main
function to run our program.
To run this program:
- Save the code in a file, e.g.,
exit-example.lisp
. - Run it using a Common Lisp implementation. For example, with SBCL:
To check the exit status in a shell:
Note that the cleanup message “This cleanup code won’t run!” is never printed due to the immediate exit.
This example demonstrates how to exit a Lisp program with a specific status code, which is useful for indicating success or failure to the calling process. It also shows that cleanup code in unwind-protect
is not executed when using an exit function, which is an important consideration when designing robust Lisp programs.