Execing Processes in Ada

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

with Ada.Command_Line;
with Ada.Directories;
with Ada.Environment_Variables;
with GNAT.OS_Lib;

procedure Exec_Process is
   use Ada.Command_Line;
   use Ada.Directories;
   use Ada.Environment_Variables;
   use GNAT.OS_Lib;

   Binary : String_Access;
   Args   : Argument_List_Access;
   Env    : Argument_List_Access;
begin
   -- Find the full path to the "ls" command
   Binary := Locate_Exec_On_Path ("ls");
   if Binary = null then
      raise Program_Error with "Could not find 'ls' command";
   end if;

   -- Set up arguments for the "ls" command
   Args := Argument_String_To_List (Binary.all & " -a -l -h");

   -- Get the current environment
   Env := Argument_String_To_List (Flatten (Environment));

   -- Replace the current process with the new one
   Exec (Binary.all, Args.all, Env.all);

   -- If Exec returns, it means there was an error
   raise Program_Error with "Exec failed";
end Exec_Process;

In this Ada program:

  1. We use the GNAT.OS_Lib package, which provides Unix-like system call interfaces for Ada.

  2. We use Locate_Exec_On_Path to find the full path of the ls command, similar to exec.LookPath in the original example.

  3. We set up the arguments for ls using Argument_String_To_List. Note that in Ada, we typically include the command name as part of the argument string.

  4. We get the current environment using Environment and convert it to the format expected by Exec.

  5. We call Exec to replace the current process with the ls command. If Exec returns, it means there was an error, so we raise an exception.

To run this program:

$ gnatmake exec_process
$ ./exec_process
total 16K
drwxr-xr-x  2 user user 4.0K May 20 10:00 .
drwxr-xr-x 10 user user 4.0K May 20 09:55 ..
-rw-r--r--  1 user user  721 May 20 10:00 exec_process.adb
-rwxr-xr-x  1 user user 17K May 20 10:00 exec_process

Note that Ada doesn’t have a direct equivalent to Go’s goroutines or Unix’s fork. However, Ada does provide robust tasking and concurrency features that can be used for similar purposes in many cases.