Working with other programs
A program can start other programs, send them text on their standard input, read what they print, set their environment, check their exit codes, and stop them when they take too long. This lesson does all of it with the Process class.
What you will learn#
- the three streams of a program: standard input, standard output and standard error,
- sending lines to a program and closing its input,
- chaining programs: the output of one is the input of another,
- environment variables and the working folder of the new program,
- exit codes:
0means success, WaitForExit(ms)as a time limit andKill.
The tutorial Time, tasks and other programs started programs and the tutorial A project: a command runner showed their output in a window. This lesson adds the input side and the control of the new program.
The program chooses the commands for the system with isWindows(): sort, find and cmd /c on Windows, sort, grep and sh -c on Linux and macOS. The output shown is from Windows.
The program#
# working with other programs - feeding standard input, environment variables, errors and exit codes, a time limit and Kill
# (the commands are chosen for the system: sort, find and cmd on Windows; sort, grep and sh on Linux and macOS)
load "dotnet.ring"
using {
"System"
"System.IO"
"System.Diagnostics"
}
# the shell of this system (set in main, used by shellArgs)
cShell = ""
cShellOption = ""
func main
# the program that keeps the lines with an "e", and the shell, for this system
cFilter = "grep"
cFilterArgs = "e"
cShell = "sh"
cShellOption = "-c"
cDirError = "ls this_folder_does_not_exist"
cWait = "sleep 5"
if isWindows()
cFilter = "find"
cFilterArgs = '"e"'
cShell = "cmd.exe"
cShellOption = "/c"
cDirError = "dir this_folder_does_not_exist"
cWait = "ping -n 6 127.0.0.1 > nul"
ok
# 1. Standard input: send lines to a program that reads its input, close the input, and read what it answers.
# The program "sort" reads lines and prints them sorted.
oSort = startProgram("sort","",True)
oSort.StandardInput.WriteLine("pear")
oSort.StandardInput.WriteLine("apple")
oSort.StandardInput.WriteLine("fig")
oSort.StandardInput.Close() # closing the input tells sort that there is no more
cSorted = oSort.StandardOutput.ReadToEnd()
oSort.WaitForExit(NULL)
? "1. sort answered: " + lines(cSorted) + " (exit code " + oSort.ExitCode + ")"
# 2. Chaining: the output of one program is the input of another. sort, then find keeps the lines that contain an 'e'.
oFirst = startProgram("sort","",True)
for cFruit in ["fig","pear","plum","apple","kiwi"]
oFirst.StandardInput.WriteLine(cFruit)
next
oFirst.StandardInput.Close()
cText = oFirst.StandardOutput.ReadToEnd()
oFirst.WaitForExit(NULL)
oSecond = startProgram(cFilter,cFilterArgs,True)
oSecond.StandardInput.Write(cText)
oSecond.StandardInput.Close()
cFound = oSecond.StandardOutput.ReadToEnd()
oSecond.WaitForExit(NULL)
? nl + "2. sorted, and only the lines with an 'e': " + lines(cFound)
# 3. Environment variables and the working folder of the new program are set before it starts.
cTemp = new Path().GetTempPath()
cEcho = "echo %GREETING%"
if not isWindows()
cEcho = "echo $GREETING"
ok
oInfo = new ProcessStartInfo().@New([ :fileName = cShell, :arguments = shellArgs(cEcho) ])
oInfo {
UseShellExecute = False
RedirectStandardOutput = True
CreateNoWindow = True
}
oInfo.EnvironmentVariables.Add("GREETING","hello from the parent program")
oInfo.WorkingDirectory = cTemp
oEnvironment = new Process().Start(oInfo)
cGreeting = oEnvironment.StandardOutput.ReadToEnd()
oEnvironment.WaitForExit(NULL)
? nl + "3. the child read the variable that the parent set: " + chomp(cGreeting)
# 4. Errors: a program writes errors to a SECOND stream (standard error) and ends with an exit code. 0 means success.
oFail = startProgram(cShell,shellArgs(cDirError),True)
cError = oFail.StandardError.ReadToEnd()
oFail.WaitForExit(NULL)
? nl + "4. a failing command: exit code " + oFail.ExitCode + ", standard error says '" + chomp(cError) + "'"
oGood = startProgram(cShell,shellArgs("exit 0"),True)
oGood.WaitForExit(NULL)
? " a command that succeeds has exit code " + oGood.ExitCode
# 5. A time limit and Kill: WaitForExit(ms) answers false when the program is still running; Kill stops it.
oSlow = startProgram(cShell,shellArgs(cWait),False)
lFinished = oSlow.WaitForExit(300)
? nl + "5. waited 300 ms for a program that runs about 5 seconds: finished = " + yesNo(lFinished)
oSlow.Kill(NULL)
oSlow.WaitForExit(NULL)
? " after Kill it has exited: " + yesNo(oSlow.HasExited)
# the arguments that make the shell run a command: cmd /c "command" or sh -c "command"
func shellArgs cCommand
return cShellOption + ' "' + cCommand + '"'
# start a program; lRedirect = True gives the program's three streams to this program (input, output, error)
func startProgram cFile, cArguments, lRedirect
oInfo = new ProcessStartInfo().@New([ :fileName = cFile, :arguments = cArguments ])
oInfo.UseShellExecute = False
oInfo.CreateNoWindow = True
if lRedirect
oInfo.RedirectStandardInput = True
oInfo.RedirectStandardOutput = True
oInfo.RedirectStandardError = True
ok
return new Process().Start(oInfo)
# the lines of a text as one line: "apple, fig, pear"
func lines cText
cResult = ""
aLines = str2list(substr(substr(cText,char(13),""),char(10),nl))
for cLine in aLines
if trim(cLine) != ""
if cResult != ""
cResult += ", "
ok
cResult += trim(cLine)
ok
next
return cResult
func chomp cText
while right(cText,1) = char(10) or right(cText,1) = char(13) or right(cText,1) = " "
cText = left(cText,len(cText) - 1)
end
return cText
func yesNo lValue
if lValue
return "yes"
ok
return "no"1. sort answered: apple, fig, pear (exit code 0)
2. sorted, and only the lines with an 'e': apple, pear
3. the child read the variable that the parent set: hello from the parent program
4. a failing command: exit code 1, standard error says 'File Not Found'
a command that succeeds has exit code 0
5. waited 300 ms for a program that runs about 5 seconds: finished = no
after Kill it has exited: yesHow it works#
Starting a program with redirected streams#
startProgram makes a ProcessStartInfo (the file, the arguments) and sets three things: UseShellExecute = False (needed to redirect), CreateNoWindow (no console window) and, when asked, RedirectStandardInput, RedirectStandardOutput and RedirectStandardError. Process.Start(info) starts it and gives a Process. After that oProcess.StandardInput, StandardOutput and StandardError are stream writers and readers: your program is now the keyboard and the screen of the other program.
Input#
sort reads lines until its input ends, then prints them sorted. So the program writes the lines (StandardInput.WriteLine) and then closes the input (StandardInput.Close()): without Close the other program keeps waiting for more and your program waits for the answer — a deadlock. Then ReadToEnd() reads the whole answer and WaitForExit(NULL) waits for the program to end.
Chaining#
Step 2 is the shell's sort | find "e" written by hand: the output of the first program is written into the input of the second. The pattern is always: write, close, read, wait.
If a program writes a lot to both its output and its error and you read only one of them, the other fills its buffer and the program stops. Read both (one with ReadToEnd() and the other after the program ended, or one in a loop), or redirect only what you need.
Environment and folder#
A new program gets a copy of the environment of its parent. oInfo.EnvironmentVariables.Add("GREETING", "…") adds a variable that only the child sees; cmd /c echo %GREETING% prints it. WorkingDirectory sets the folder in which the program starts. The folder is put into a variable first because a new on the right side of a property assignment does not keep the assignment (Rules and limits).
Exit codes and errors#
A program tells its result with an exit code: 0 is success, anything else a problem (the program decides which number means what). A program writes its error messages to the standard error stream, separate from its normal output: step 4 reads File Not Found from StandardError and sees exit code 1. oProcess.ExitCode is available after the program ended.
A time limit#
WaitForExit(300) waits at most 300 ms and answers true if the program ended, false if it is still running. Kill(NULL) stops it at once (use it only when you must: the program gets no chance to clean up); then HasExited is true.
What you learned#
- redirecting the three streams,
- the write, close, read, wait pattern,
- environment variables and
WorkingDirectory, - exit codes and standard error,
WaitForExit(ms)andKill.
Exercises#
- Write a function
runAndCapture(cFile, cArguments)that returns[exit code, output, error]. - Run
pingwith a time limit of two seconds and stop it if it is slower. - Write a little program that reads lines from its input and prints them in upper case (the child of the tutorial Two programs talking) and feed it from the parent.
- Chain three programs: sort, remove duplicates (
uniqorsort /unique), count lines.