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:
We use the
GNAT.OS_Libpackage, which provides Unix-like system call interfaces for Ada.We use
Locate_Exec_On_Pathto find the full path of thelscommand, similar toexec.LookPathin the original example.We set up the arguments for
lsusingArgument_String_To_List. Note that in Ada, we typically include the command name as part of the argument string.We get the current environment using
Environmentand convert it to the format expected byExec.We call
Execto replace the current process with thelscommand. IfExecreturns, 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_processNote 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.