Execing Processes in Fortress

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

In this example, we’ll look at executing external processes in Fortress. Sometimes we want to completely replace the current Fortress process with another one. To do this, we’ll use Fortress’s implementation of the classic exec function.

import system
import os
import syscall

run() =
    # For our example, we'll exec `ls`. Fortress requires an
    # absolute path to the binary we want to execute, so
    # we'll use `which` to find it (probably `/bin/ls`).
    binary = system.run("which ls").strip()
    if binary.isEmpty() then
        error("Could not find ls binary")
    end

    # `exec` requires arguments in array form (as
    # opposed to one big string). We'll give `ls` a few
    # common arguments. Note that the first argument should
    # be the program name.
    args = ["ls", "-a", "-l", "-h"]

    # `exec` also needs a set of environment variables
    # to use. Here we just provide our current
    # environment.
    env = os.environ()

    # Here's the actual `syscall.exec` call. If this call is
    # successful, the execution of our process will end
    # here and be replaced by the `/bin/ls -a -l -h`
    # process. If there is an error, it will throw an exception.
    syscall.exec(binary, args, env)
end

When we run our program, it is replaced by ls.

$ fortress execing_processes.fss
total 16
drwxr-xr-x  4 user 136B Oct 3 16:29 .
drwxr-xr-x 91 user 3.0K Oct 3 12:50 ..
-rw-r--r--  1 user 1.3K Oct 3 16:28 execing_processes.fss

Note that Fortress, like many high-level languages, does not offer a classic Unix fork function. Usually this isn’t an issue though, since starting threads, spawning processes, and exec’ing processes covers most use cases for fork.