Environment and processes in Pascal
last modified November 18, 2026 Free Pascal 3.2.2
A command-line program inherits an environment: a list of name-value strings
such as HOME, PATH, and LANG. It also
sits in a directory, has a configuration directory assigned by the operating
system, and can start other programs. Pascal exposes these facilities through
SysUtils for the environment and directories and through the
Process unit for child processes. This article reads and
distinguishes environment variables, finds the config and temp directories,
captures a child's output, handles a failed launch, and splits PATH
into its entries.
Reading environment variables
GetEnvironmentVariable(Name) returns the value of a variable, or
an empty string when the variable is not set. The function has no status
result, so an empty value and a missing variable look the same; a program that
must distinguish them has to treat an empty string as unset.
GetEnvironmentVariableCount and GetEnvironmentString
enumerate the whole environment as a list of NAME=value strings.
program env;
{$mode objfpc}{$H+}
uses SysUtils;
var
Count: Integer;
begin
WriteLn('HOME: [', GetEnvironmentVariable('HOME'), ']');
WriteLn('SHELL: [', GetEnvironmentVariable('SHELL'), ']');
WriteLn('MISSING: [', GetEnvironmentVariable('ZETCODE_MISSING'), ']');
Count := GetEnvironmentVariableCount;
WriteLn('variables: ', Count);
WriteLn('first: ', GetEnvironmentString(1));
end.
The missing variable prints as an empty pair of brackets, exactly like a
variable that is set to the empty string would. The first entry in the
environment is SHELL=/bin/bash in this run, but the order is not
guaranteed and differs between systems. The count of 117 variables is also
specific to this shell; a program should never depend on either value.
$ fpc -gl env.pas $ ./env HOME: [/home/jano] SHELL: [/bin/bash] MISSING: [] variables: 117 first: SHELL=/bin/bash
Config and temp directories
Hard-coding $HOME/.config works on Linux but not on Windows or
macOS, where the convention is different. GetAppConfigDir returns
the per-user directory for the application, creating the path from the
platform rules and the program name, and GetAppConfigFile returns
a suitable configuration file name in that directory. The Boolean argument
selects the system-wide directory when it is True.
program appdirs;
{$mode objfpc}{$H+}
uses SysUtils;
var
Home, ConfigDir, ConfigFile, Temp: string;
begin
Home := GetEnvironmentVariable('HOME');
ConfigDir := GetAppConfigDir(False);
ConfigFile := GetAppConfigFile(False);
Temp := GetTempDir;
WriteLn('config dir: ', StringReplace(ConfigDir, Home, '~', []));
WriteLn('config file: ', StringReplace(ConfigFile, Home, '~', []));
WriteLn('temp dir: ', Temp);
WriteLn('executable: ', ExtractFileName(ParamStr(0)));
end.
On this Linux machine the config directory is ~/.config/appdirs/
and the file is ~/.config/appdirs.cfg, both derived from the
program name. The StringReplace call only shortens the path for
display; the real value is absolute. GetTempDir returns
/tmp/, and ExtractFileName(ParamStr(0)) reduces the
program path to its last component, which is useful in messages and help
text. The directory is not created automatically: the program must call
ForceDirectories before writing into it.
$ fpc -gl appdirs.pas $ ./appdirs config dir: ~/.config/appdirs/ config file: ~/.config/appdirs.cfg temp dir: /tmp/ executable: appdirs
Running a child process
TProcess starts an external program and gives the parent control
over its arguments, environment, working directory, and input and output
streams. The Executable property names the program, and
Parameters is a string list of arguments. The Options
set controls behaviour: poUsePipes connects the child's standard
streams to pipes owned by the parent, and poWaitOnExit makes
Execute return only after the child has finished.
program runprocess;
{$mode objfpc}{$H+}
uses SysUtils, Process;
var
P: TProcess;
Buffer: array[0..4095] of Byte;
N: LongInt;
S: string;
begin
P := TProcess.Create(nil);
try
P.Executable := 'sh';
P.Parameters.Add('-c');
P.Parameters.Add('echo hello from child; echo second line');
P.Options := [poUsePipes, poWaitOnExit];
P.Execute;
N := P.Output.Read(Buffer[0], SizeOf(Buffer));
SetLength(S, N);
Move(Buffer[0], S[1], N);
Write('captured: ', S);
WriteLn('bytes: ', N);
WriteLn('exit status: ', P.ExitStatus);
finally
P.Free;
end;
end.
The child's output is read from P.Output, which is a stream, not a
text file, so the program copies the bytes into a string with Move.
ExitStatus is the value returned by the child's exit:
zero here. Reading only once works because the output is tiny; a child that
writes more than the pipe buffer holds would block until the parent reads, so
production code reads in a loop while the process runs. Setting
poWaitOnExit and reading a large output afterwards is a classic
deadlock.
$ fpc -gl runprocess.pas $ ./runprocess captured: hello from child second line bytes: 29 exit status: 0
ExecuteProcess and failures
ExecuteProcess is a shortcut that starts a program, waits for it,
and returns its exit status without creating a TProcess object.
It takes the executable and an array of arguments. In Free Pascal 3.2.2 the
shortcut does not search PATH, so the executable must be given as
an absolute path or as a name the operating system can resolve; TProcess
does perform the search. A missing executable raises EOSError.
program execproc;
{$mode objfpc}{$H+}
uses SysUtils, Process;
var
Code: Integer;
begin
Code := ExecuteProcess('/bin/sh', ['-c', 'exit 3']);
WriteLn('child status: ', Code);
try
ExecuteProcess('zetcode-no-such-program', []);
except
on E: EOSError do
WriteLn('failed: ', E.ClassName, ': ', E.Message);
end;
end.
The first call runs a shell that exits with status 3, and the parent receives
that number. The second call names a program that does not exist; the
exception carries the name and the operating system error code 127, which
means "command not found". Catching EOSError is the correct guard
for a launch that may fail, while an invalid argument usually makes the child
fail with a non-zero status rather than raising in the parent.
$ fpc -gl execproc.pas $ ./execproc child status: 3 failed: EOSError: Failed to execute "zetcode-no-such-program", error code: 127
Splitting PATH
PATH is a list of directories separated by PathSeparator,
which is : on Unix and ; on Windows. A program that
wants to search for an executable itself must split the string and test each
directory. The example counts the entries and checks whether
/usr/bin appears; it uses Pos and Delete
to consume the string from the left.
program pathenv;
{$mode objfpc}{$H+}
uses SysUtils;
var
Path, Part: string;
P, Count: Integer;
begin
Path := GetEnvironmentVariable('PATH');
WriteLn('PATH set: ', Path <> '');
Count := 0;
repeat
P := Pos(PathSeparator, Path);
if P > 0 then
begin
Part := Copy(Path, 1, P - 1);
Delete(Path, 1, P);
end
else
begin
Part := Path;
Path := '';
end;
if Part <> '' then
Inc(Count);
until Path = '';
WriteLn('entries: ', Count);
WriteLn('has /usr/bin: ', Pos('/usr/bin', GetEnvironmentVariable('PATH')) > 0);
end.
The loop takes the text before the first separator, removes it together with
the separator, and repeats until no separator remains. Empty entries, which
occur with a leading, trailing, or doubled separator, are skipped. The count
of 46 is the number of directories in this shell's PATH; the
/usr/bin test is a simple substring search and would also match
/usr/bin/../local or /opt/usr/bin, so a real lookup
compares complete directory names.
$ fpc -gl pathenv.pas $ ./pathenv PATH set: TRUE entries: 46 has /usr/bin: TRUE
Next steps
The command-line arguments
article reads the values that the shell passes at startup, and the
exceptions article explains the
try..except form used for the failed launch. The
reading input article covers files and
standard input, and the units article shows how a program is split
into separately compiled files.
Source
Free Pascal: GetEnvironmentVariable
In this article we read environment variables and enumerated the environment,
found platform-specific config and temp directories, captured a child's output
through a pipe, handled a failed launch, and split PATH into its
entries. The series continues with
error handling and exceptions in Pascal.
Author
List all Pascal tutorials.