Execing Processes in Lisp

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

Our example demonstrates how to replace the current process with another one using Lisp. This is similar to the classic exec function in Unix-like operating systems.

(defun main ()
  ;; For our example, we'll exec 'ls'. We need to find the full path to the binary.
  (let ((binary (or (sb-ext:find-executable-in-search-path "ls")
                    (error "Cannot find 'ls' executable"))))

    ;; We'll give 'ls' a few common arguments. Note that the first argument should
    ;; be the program name.
    (let ((args (list "ls" "-a" "-l" "-h")))

      ;; We also need to provide the current environment variables.
      (let ((env (sb-ext:posix-environ)))

        ;; Here's the actual call to replace the current process.
        ;; If this call is successful, the execution of our process will end
        ;; here and be replaced by the 'ls -a -l -h' process.
        (sb-ext:run-program binary args :environment env :search t :wait nil)))))

(main)

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

$ sbcl --script execing-processes.lisp
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.lisp

Note that Lisp doesn’t offer a classic Unix fork function either. However, Lisp implementations often provide ways to spawn new processes or execute external programs, which cover most use cases for fork.

In this example, we’re using Steel Bank Common Lisp (SBCL) and its extensions to achieve functionality similar to the original Go program. The sb-ext:find-executable-in-search-path function is used to locate the ls binary, similar to exec.LookPath in Go. The sb-ext:run-program function is used to execute the new process, replacing the current one.

Remember that the exact implementation might vary depending on the Lisp implementation you’re using. This example uses SBCL-specific functions, but other Lisp implementations may have different ways to achieve the same result.