Execing Processes in Erlang

Here’s the translation of the Go code to Erlang, formatted in Markdown suitable for Hugo:

In this example, we’ll look at executing external processes. Sometimes we want to completely replace the current Erlang process with another (perhaps non-Erlang) one. To do this, we’ll use Erlang’s implementation of the classic os:cmd/1 function.

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

main() ->
    % For our example, we'll execute 'ls'. Erlang doesn't require an
    % absolute path to the binary we want to execute, so we can use
    % the command name directly.
    Command = "ls",

    % We'll give 'ls' a few common arguments.
    Args = "-alh",

    % Combine the command and arguments
    FullCommand = Command ++ " " ++ Args,

    % Here's the actual os:cmd/1 call. If this call is successful,
    % it will return the output of the command as a string.
    case os:cmd(FullCommand) of
        [] ->
            io:format("Command execution failed~n");
        Output ->
            io:format("~s~n", [Output])
    end.

When we run our program, it will execute the ls command and print its output.

$ erl -noshell -s execing_processes main -s init stop
total 16K
drwxr-xr-x  2 user user 4.0K Jun 15 10:00 .
drwxr-xr-x 20 user user 4.0K Jun 15 09:59 ..
-rw-r--r--  1 user user  551 Jun 15 10:00 execing_processes.erl

Note that Erlang doesn’t offer a direct equivalent to Go’s syscall.Exec. The os:cmd/1 function runs the command in a separate OS process and returns its output, rather than replacing the current Erlang process. If you need more control over process execution, you might want to look into Erlang’s open_port/2 function or the erlang:open_port/2 BIF, which allow for more sophisticated interprocess communication.

Also, Erlang doesn’t have a direct equivalent to Go’s exec.LookPath. The operating system’s shell is responsible for finding the executable in the system path when using os:cmd/1.

Erlang’s approach to concurrency is quite different from many other languages. It uses lightweight processes and message passing, which often eliminates the need for explicit process spawning or execution as seen in other languages.