Exit in Erlang

Here’s an idiomatic Erlang example demonstrating the concept of exiting a program with a specific status code:

-module(exit_example).
-export([main/0]).

main() ->
    % This function will not be called due to the early exit
    _ = erlang:process_flag(trap_exit, true),
    spawn_link(fun() ->
        timer:sleep(1000),
        io:format("This will never be printed~n")
    end),

    % Exit with status 3
    erlang:halt(3).

This Erlang program demonstrates how to exit a program with a specific status code. Let’s break it down:

  1. We define a module named exit_example and export the main/0 function.

  2. In the main/0 function, we set up a trap_exit flag and spawn a linked process. This is analogous to the defer statement in the original example, as it represents code that won’t be executed due to the early exit.

  3. We use erlang:halt(3) to immediately terminate the Erlang runtime system with the exit status 3. This is equivalent to os.Exit(3) in the original Go example.

To run this program:

  1. Save the code in a file named exit_example.erl.
  2. Compile the code using the Erlang compiler:
$ erlc exit_example.erl
  1. Run the compiled code:
$ erl -noshell -s exit_example main -s init stop
  1. Check the exit status:
$ echo $?
3

Note that the message “This will never be printed” is not displayed because the program exits before the spawned process has a chance to execute.

In Erlang, unlike languages like C, the return value from the main function is not used to indicate the exit status. Instead, we use erlang:halt/1 to explicitly set the exit status.

It’s worth noting that in most Erlang applications, you typically don’t exit the entire VM like this. Erlang is designed for building long-running, fault-tolerant systems. However, this example demonstrates how you would exit with a specific status code if needed, which might be useful in scripts or short-lived programs.