Execing Processes in Pascal
Here’s the translation of the Go code to Pascal, with explanations in Markdown format suitable for Hugo:
In this example, we’ll look at executing external processes. Sometimes we want to completely replace the current Pascal process with another one. To do this, we’ll use Pascal’s implementation of the classic exec
function.
program ExecingProcesses;
uses
SysUtils, Process;
var
ExternalProcess: TProcess;
ExitCode: Integer;
begin
// For our example we'll exec 'ls'. We'll use the 'FindDefaultExecutablePath'
// function to find the full path of the 'ls' command.
try
ExternalProcess := TProcess.Create(nil);
ExternalProcess.Executable := FindDefaultExecutablePath('ls');
// We'll give 'ls' a few common arguments. Note that the first argument
// should be the program name.
ExternalProcess.Parameters.Add('-a');
ExternalProcess.Parameters.Add('-l');
ExternalProcess.Parameters.Add('-h');
// Set up the environment variables for the process.
// Here we just provide our current environment.
ExternalProcess.Environment := GetEnvironmentVariables;
// Execute the process
ExternalProcess.Execute;
// Wait for the process to finish and get its exit code
ExternalProcess.WaitOnExit;
ExitCode := ExternalProcess.ExitCode;
if ExitCode <> 0 then
raise Exception.Create('Process exited with code ' + IntToStr(ExitCode));
except
on E: Exception do
WriteLn('Error: ', E.Message);
end;
end.
When we run our program, it will execute the ls
command with the specified arguments.
$ fpc execing-processes.pas
$ ./execing-processes
total 16
drwxr-xr-x 4 mark 136B Oct 3 16:29 .
drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
-rw-r--r-- 1 mark 1.3K Oct 3 16:28 execing-processes.pas
-rwxr-xr-x 1 mark 75K Oct 3 16:29 execing-processes
Note that Pascal doesn’t offer a classic Unix fork
function. However, the TProcess
class from the Process
unit provides functionality for starting and managing external processes, which covers most use cases for process creation and execution in Pascal programs.