Exit in Fortress

Here’s an idiomatic Fortress code example that demonstrates the concept of exiting a program with a specific status code:

component main
  export Executable

  run() = 
    println("Program starting...")
    
    # This will not be executed due to the exit call
    finally(fn() -> println("Program ending..."))
    
    # Exit the program with status code 3
    exit(3)
  end
end

In Fortress, we can demonstrate the concept of exiting a program with a specific status code using the exit function. Here’s an explanation of the code:

  1. We define a main component that exports the Executable trait, which is required for the program to be runnable.

  2. Inside the run function (which is the entry point of a Fortress program), we first print a message indicating the program is starting.

  3. We use the finally function to register a cleanup action. In Fortress, finally is similar to defer in some other languages. It schedules a function to be called when the current function exits normally.

  4. We then call exit(3), which immediately terminates the program with the status code 3.

  5. The cleanup action registered with finally will not be executed because exit terminates the program immediately.

To run this Fortress program:

  1. Save the code in a file named ExitExample.fss.
  2. Use the Fortress compiler to compile the program:
$ fortc ExitExample.fss
  1. Run the compiled program:
$ fort ExitExample
Program starting...
  1. Check the exit status:
$ echo $?
3

Note that the “Program ending…” message is never printed because the exit function terminates the program before the finally block can be executed.

In Fortress, like in many other languages, using exit to terminate a program should be done judiciously. It’s often better to allow the program to terminate naturally by reaching the end of the run function, which gives finally blocks and other cleanup mechanisms a chance to execute.

This example demonstrates how to use exit in Fortress to terminate a program with a specific status code, and shows that cleanup actions registered with finally are not executed when exit is called.