ZetCode

Modula-2 environment and processes

last modified November 27, 2026 Modula-2

Neither PIM nor ISO Modula-2 has a library for environment variables or for running other programs. GNU Modula-2 provides them in two modules of its own: Environment reads environment variables, and libc gives access to functions of the C library such as system and setenv. Programs that use them compile only with gm2. The rest of each example uses the ISO library, as in the previous articles.

Reading a variable

Environment.GetEnvironment copies the value of an environment variable into a character array and returns TRUE if the variable exists.

mode.mod
MODULE mode;
FROM Environment IMPORT GetEnvironment;
FROM STextIO IMPORT WriteString, WriteLn;

VAR
  value: ARRAY [0..63] OF CHAR;

BEGIN
  IF GetEnvironment("APP_MODE", value) THEN
    WriteString("APP_MODE is "); WriteString(value)
  ELSE
    WriteString("APP_MODE is not set, using production")
  END;
  WriteLn
END mode.

Without APP_MODE the function returns FALSE, and the program falls back to a default. The shell syntax APP_MODE=test ./mode sets the variable for a single run. A value longer than the array is truncated without notice, so the array should be large enough for any sensible value.

$ gm2 -fiso mode.mod -o mode
$ ./mode
APP_MODE is not set, using production
$ APP_MODE=test ./mode
APP_MODE is test

Settings from the environment

An environment variable is text, like a command-line argument. The next program takes the width of a ruler from RULER_WIDTH and converts it with ToInt from the Numbers module of the reading input article.

ruler.mod
MODULE ruler;
FROM Environment IMPORT GetEnvironment;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM Numbers IMPORT ToInt;

CONST
  Default = 30;

VAR
  value: ARRAY [0..15] OF CHAR;
  width, i: INTEGER;

BEGIN
  IF NOT GetEnvironment("RULER_WIDTH", value) THEN
    width := Default
  ELSIF NOT ToInt(value, width) OR (width < 1) OR (width > 200) THEN
    WriteString("bad RULER_WIDTH, using "); WriteInt(Default, 0); WriteLn;
    width := Default
  END;
  FOR i := 1 TO width DO
    IF i MOD 10 = 0 THEN WriteChar('|')
    ELSIF i MOD 5 = 0 THEN WriteChar('+')
    ELSE WriteChar('-')
    END
  END;
  WriteLn
END ruler.

A missing variable gives the default width quietly. A variable that is not a number in the allowed range gives the default too, but with a message, because the user meant to set something. The ruler marks every fifth position with + and every tenth with |.

$ gm2 -fiso -c Numbers.mod
$ gm2 -fiso ruler.mod Numbers.o -o ruler
$ ./ruler
----+----|----+----|----+----|
$ RULER_WIDTH=42 ./ruler
----+----|----+----|----+----|----+----|--
$ RULER_WIDTH=wide ./ruler
bad RULER_WIDTH, using 30
----+----|----+----|----+----|

The exit status

A program returns an exit status to the shell: 0 for success, another number for failure. gm2 extends the standard procedure HALT with an optional parameter, the exit status.

found.mod
MODULE found;
FROM ProgramArgs IMPORT ArgChan, IsArgPresent, NextArg;
FROM StreamFile IMPORT ChanId, Open, Close, OpenResults, read;
FROM TextIO IMPORT ReadString;
FROM STextIO IMPORT WriteString, WriteLn;

VAR
  name: ARRAY [0..255] OF CHAR;
  cid: ChanId;
  res: OpenResults;

BEGIN
  NextArg;
  IF NOT IsArgPresent() THEN
    WriteString("usage: found file"); WriteLn;
    HALT(2)
  END;
  ReadString(ArgChan(), name);
  Open(cid, name, read, res);
  IF res = opened THEN
    Close(cid);
    WriteString(name); WriteString(" can be read"); WriteLn
  ELSE
    WriteString(name); WriteString(" cannot be read"); WriteLn;
    HALT(1)
  END
END found.

The program checks whether a file can be read. It ends with status 0 when the body finishes normally, 1 when the file cannot be read and 2 when the argument is missing. HALT(n) runs the termination code of the modules, so all pending output is written. Plain HALT without a parameter calls the C function abort and ends the program with status 134, like a runtime error. The shell variable $? holds the status of the last command.

$ gm2 -fiso found.mod -o found
$ ./found note.txt
note.txt can be read
$ echo $?
0
$ ./found missing.txt
missing.txt cannot be read
$ echo $?
1
$ ./found
usage: found file
$ echo $?
2

Leaving with libc.exit

libc.exit calls the C function exit directly and also sets the exit status. It skips the termination code of the modules.

quit.mod
MODULE quit;
FROM STextIO IMPORT WriteString, WriteLn;
FROM libc IMPORT exit;

BEGIN
  WriteString("first line"); WriteLn;
  WriteString("second line"); WriteLn;
  exit(5)
END quit.

The status is 5, but the output is incomplete. cat -A marks the end of every line with $, and the second line has none: the line mark was still pending in the output channel when the C library ended the process. HALT(n) is the better way to set the status.

$ gm2 -fiso quit.mod -o quit
$ ./quit
first line
second line
$ echo $?
5
$ ./quit | cat -A
first line$
second line

Running a command

libc.system passes a command to the shell and waits until it finishes. It is a C function, and it takes the address of a 0C-terminated string, which ADR from the SYSTEM module provides. The low-level programming article covers SYSTEM, and calling C declares C functions of its own.

shell.mod
MODULE shell;
FROM SYSTEM IMPORT ADR;
FROM libc IMPORT system;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
IMPORT IOChan, StdChans;

VAR
  status: INTEGER;

BEGIN
  WriteString("running ls"); WriteLn;
  IOChan.Flush(StdChans.StdOutChan());
  status := system(ADR("ls *.txt"));
  WriteString("ls returned "); WriteInt(status, 0); WriteLn
END shell.

gm2 stores a string constant with a terminating 0C, so ADR("ls *.txt") is a valid C string. The shell expands the wildcard, and ls writes to the same terminal as the program. The program flushes its own output first, so that its line comes before the output of the command. system returns 0 because ls succeeded.

$ gm2 -fiso shell.mod -o shell
$ ./shell
running ls
note.txt
steps.txt
ls returned 0

The status of a command

The value returned by system is the raw wait status of the process. On Linux, the exit status of the command is that value divided by 256.

status.mod
MODULE status;
FROM SYSTEM IMPORT ADR;
FROM libc IMPORT system;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM Strings IMPORT Assign;
IMPORT IOChan, StdChans;

PROCEDURE Run(command: ARRAY OF CHAR);
VAR
  cmd: ARRAY [0..255] OF CHAR;
  wait: INTEGER;
BEGIN
  Assign(command, cmd);
  IOChan.Flush(StdChans.StdOutChan());
  wait := system(ADR(cmd));
  WriteString(command); WriteString(": raw ");
  WriteInt(wait, 0); WriteString(", exit status ");
  WriteInt(wait DIV 256, 0); WriteLn
END Run;

BEGIN
  Run("true");
  Run("false");
  Run("exit 3");
  Run("grep -q Lilith note.txt");
  Run("no-such-command 2> /dev/null")
END status.

Run copies the command into a fixed array with Assign, which guarantees the 0C terminator that system needs, and the open array parameter cannot be assigned directly. false exits with 1 and exit 3 with 3. grep -q reports a match through its status alone, and the shell returns 127 for a command it cannot find.

$ gm2 -fiso status.mod -o status
$ ./status
true: raw 0, exit status 0
false: raw 256, exit status 1
exit 3: raw 768, exit status 3
grep -q Lilith note.txt: raw 0, exit status 0
no-such-command 2> /dev/null: raw 32512, exit status 127

Capturing the output

system does not return the output of the command. The command can redirect its output into a file, and the program reads the file afterwards.

capture.mod
MODULE capture;
FROM SYSTEM IMPORT ADR;
FROM libc IMPORT system;
FROM StreamFile IMPORT ChanId, Open, Close, OpenResults, read;
FROM TextIO IMPORT ReadString, SkipLine;
FROM IOResult IMPORT ReadResult, ReadResults;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM Strings IMPORT Length;

VAR
  cid: ChanId;
  res: OpenResults;
  line: ARRAY [0..255] OF CHAR;
  n: CARDINAL;

BEGIN
  IF system(ADR("sort -t, -k2 -n -r grades.csv > sorted.tmp")) # 0 THEN
    WriteString("sort failed"); WriteLn;
    HALT(1)
  END;
  Open(cid, "sorted.tmp", read, res);
  IF res # opened THEN
    WriteString("cannot open sorted.tmp"); WriteLn;
    HALT(1)
  END;
  n := 0;
  LOOP
    ReadString(cid, line);
    IF (ReadResult(cid) = endOfInput) AND (Length(line) = 0) THEN EXIT END;
    INC(n);
    WriteCard(n, 2); WriteString(". "); WriteString(line); WriteLn;
    SkipLine(cid)
  END;
  Close(cid);
  IF system(ADR("rm sorted.tmp")) # 0 THEN HALT(1) END
END capture.

sort orders the grades file by the second comma-separated field, numerically and in reverse, and writes the result to sorted.tmp. The program reads the file line by line as in the files article, numbers the lines, and removes the file with another command. A failed command ends the program with status 1.

$ gm2 -fiso capture.mod -o capture
$ cat grades.csv
Agnes,72
Boris,45
Clara,91
Dusan,60
Eva,88
Filip,79
$ ./capture
 1. Clara,91
 2. Eva,88
 3. Filip,79
 4. Agnes,72
 5. Dusan,60
 6. Boris,45

Setting a variable

Commands started with system inherit the environment of the program. Environment also exports PutEnvironment, and libc exports the C function setenv.

setvar.mod
MODULE setvar;
FROM SYSTEM IMPORT ADR;
FROM libc IMPORT system, setenv;
FROM Environment IMPORT PutEnvironment, GetEnvironment;
FROM STextIO IMPORT WriteString, WriteLn;
IMPORT IOChan, StdChans;

VAR
  value: ARRAY [0..63] OF CHAR;

BEGIN
  IF PutEnvironment("COLOR=blue") THEN
    WriteString("PutEnvironment succeeded"); WriteLn
  END;
  IF NOT GetEnvironment("COLOR", value) THEN
    WriteString("but COLOR is not set"); WriteLn
  END;
  IF setenv(ADR("SHAPE"), ADR("round"), 1) = 0 THEN
    WriteString("setenv succeeded"); WriteLn
  END;
  IOChan.Flush(StdChans.StdOutChan());
  IF system(ADR('echo "child: COLOR=$COLOR SHAPE=$SHAPE"')) # 0 THEN
    HALT(1)
  END
END setvar.

PutEnvironment reports success, but in gm2 15.2 the variable is not set: the procedure hands the C library the address of a temporary copy of its parameter, which is gone when it returns. Neither the program nor the child sees COLOR. setenv copies the name and the value, and the child prints SHAPE correctly. Its last parameter, 1, allows it to replace an existing value.

$ gm2 -fiso setvar.mod -o setvar
$ ./setvar
PutEnvironment succeeded
but COLOR is not set
setenv succeeded
child: COLOR= SHAPE=round

A build runner

The last program runs the commands listed in a file one after another. It stops at the first command that fails and exits with that command's status, as make does.

steps.mod
MODULE steps;
FROM SYSTEM IMPORT ADR;
FROM libc IMPORT system;
FROM StreamFile IMPORT ChanId, Open, Close, OpenResults, read;
FROM TextIO IMPORT ReadString, SkipLine;
FROM IOResult IMPORT ReadResult, ReadResults;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard, WriteInt;
FROM Strings IMPORT Length;
IMPORT IOChan, StdChans;

VAR
  cid: ChanId;
  res: OpenResults;
  cmd: ARRAY [0..255] OF CHAR;
  n: CARDINAL;
  status: INTEGER;

BEGIN
  Open(cid, "steps.txt", read, res);
  IF res # opened THEN
    WriteString("cannot open steps.txt"); WriteLn;
    HALT(2)
  END;
  n := 0;
  LOOP
    ReadString(cid, cmd);
    IF (ReadResult(cid) = endOfInput) AND (Length(cmd) = 0) THEN EXIT END;
    SkipLine(cid);
    INC(n);
    WriteString("step "); WriteCard(n, 0); WriteString(": ");
    WriteString(cmd); WriteLn;
    IOChan.Flush(StdChans.StdOutChan());
    status := system(ADR(cmd)) DIV 256;
    IF status # 0 THEN
      WriteString("step "); WriteCard(n, 0);
      WriteString(" failed with status "); WriteInt(status, 0); WriteLn;
      Close(cid);
      HALT(status)
    END
  END;
  Close(cid);
  WriteString("all "); WriteCard(n, 0); WriteString(" steps done"); WriteLn
END steps.

Each line of steps.txt is a command. The program prints it, flushes, and runs it; DIV 256 turns the wait status into the exit status. The fifth step fails because Pascal does not occur in note.txt, so the runner closes the file and passes the status 1 on to the shell with HALT; the last step never runs.

$ gm2 -fiso steps.mod -o steps
$ cat steps.txt
echo compiling the Numbers module
gm2 -fiso -c Numbers.mod
test -f Numbers.o
grep -c Lilith note.txt
grep -q Pascal note.txt
echo not reached
$ ./steps
step 1: echo compiling the Numbers module
compiling the Numbers module
step 2: gm2 -fiso -c Numbers.mod
step 3: test -f Numbers.o
step 4: grep -c Lilith note.txt
1
step 5: grep -q Pascal note.txt
step 5 failed with status 1
$ echo $?
1

Source

The GNU Modula-2 manual

The base libraries of GNU Modula-2

In this article we have read environment variables with GetEnvironment, used them as settings with defaults, returned an exit status with HALT, run commands with libc.system, decoded their status, captured their output in a file, set a variable for child processes with setenv, and written a small build runner. The command-line arguments article covers the other way to configure a program, and the files article the file handling used here.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Modula-2 tutorials.