Returns the current working directory of the calling process.
22.9. Processes
22.9.1. Current Process
Sets the current working directory of the calling process.
Terminates the current process with the provided exit code. 0 indicates success, all other values
indicate failure.
Returns the process ID of the calling process.
22.9.2. Running Processes
There are three primary ways to run other programs from Lean:
IO.Process.runsynchronously executes another program, returning its standard output as a string. It throws an error if the process exits with an error code other than0.IO.Process.outputsynchronously executes another program with an empty standard input, capturing its standard output, standard error, and exit code. No error is thrown if the process terminates unsuccessfully.IO.Process.spawnstarts another program asynchronously and returns a data structure that can be used to access the process's standard input, output, and error streams.
Runs a process to completion, blocking until it terminates. The child process is run with a null standard input or the specified input if provided, which it need not read in full. If the child process terminates successfully with exit code 0, its standard output is returned.
An exception is thrown if the child terminates with any other exit code; its message includes the
standard error, with invalid UTF-8 replaced by � (U+FFFD). An exception is also thrown if the
standard output is not valid UTF-8.
The specifications of standard input, output, and error handles in args are ignored.
Like IO.Process.Child.wait, this function throws an error on the thread of the event loop.
Running a Program
When run, this program concatenates its own source code with itself twice using the Unix tool cat.
-- Main.lean begins here
def main : IO Unit := do
let src2 ← IO.Process.run {cmd := "cat", args := #["Main.lean", "Main.lean"]}
IO.println src2
-- Main.lean ends here
Its output is:
stdout-- Main.lean begins heredef main : IO Unit := do let src2 ← IO.Process.run {cmd := "cat", args := #["Main.lean", "Main.lean"]} IO.println src2-- Main.lean ends here-- Main.lean begins heredef main : IO Unit := do let src2 ← IO.Process.run {cmd := "cat", args := #["Main.lean", "Main.lean"]} IO.println src2-- Main.lean ends hereRunning a Program on a File
This program uses the Unix utility grep as a filter to find four-digit palindromes.
It creates a file that contains all numbers from 0 through 9999, and then invokes grep on it, reading the result from its standard output.
def main : IO Unit := do
-- Feed the input to the subprocess
IO.FS.withFile "numbers.txt" .write fun h =>
for i in [0:10000] do
h.putStrLn (toString i)
let palindromes ← IO.Process.run {
cmd := "grep",
args := #[r#"^\([0-9]\)\([0-9]\)\2\1$"#, "numbers.txt"]
}
let count := palindromes.trimAscii.split "\n" |>.length
IO.println s!"There are {count} four-digit palindromes."
Its output is:
stdoutThere are 90 four-digit palindromes.IO.Process.output (args : IO.Process.SpawnArgs) (input? : Option String := none) : IO IO.Process.OutputIO.Process.output (args : IO.Process.SpawnArgs) (input? : Option String := none) : IO IO.Process.Output
Runs a process to completion and captures its output and exit code. The child process is run with a null standard input or the specified input if provided, and the current process blocks until it has run to completion. The child need not read all of its input.
Once the child has exited, an exception is thrown if its standard output or standard error is not
valid UTF-8. Use IO.Process.binOutput to capture output that need not be UTF-8.
The specifications of standard input, output, and error handles in args are ignored.
Like IO.Process.Child.wait, this function throws an error on the thread of the event loop.
Checking Exit Codes
When run, this program first invokes cat on a nonexistent file and displays the resulting error code.
It then concatenates its own source code with itself twice using the Unix tool cat.
-- Main.lean begins here
def main : IO UInt32 := do
let src1 ← IO.Process.output {cmd := "cat", args := #["Nonexistent.lean"]}
IO.println s!"Exit code from failed process: {src1.exitCode}"
let src2 ← IO.Process.output {cmd := "cat", args := #["Main.lean", "Main.lean"]}
if src2.exitCode == 0 then
IO.println src2.stdout
else
IO.eprintln "Concatenation failed"
return 1
return 0
-- Main.lean ends here
Its output is:
stdoutExit code from failed process: 1-- Main.lean begins heredef main : IO UInt32 := do let src1 ← IO.Process.output {cmd := "cat", args := #["Nonexistent.lean"]} IO.println s!"Exit code from failed process: {src1.exitCode}" let src2 ← IO.Process.output {cmd := "cat", args := #["Main.lean", "Main.lean"]} if src2.exitCode == 0 then IO.println src2.stdout else IO.eprintln "Concatenation failed" return 1 return 0-- Main.lean ends here-- Main.lean begins heredef main : IO UInt32 := do let src1 ← IO.Process.output {cmd := "cat", args := #["Nonexistent.lean"]} IO.println s!"Exit code from failed process: {src1.exitCode}" let src2 ← IO.Process.output {cmd := "cat", args := #["Main.lean", "Main.lean"]} if src2.exitCode == 0 then IO.println src2.stdout else IO.eprintln "Concatenation failed" return 1 return 0-- Main.lean ends hereStarts a child process with the provided configuration. The child process is spawned using operating system primitives, and it can be written in any language.
The child process runs in parallel with the parent. Its exit is detected in the background, so it
does not linger as a zombie process even if IO.Process.Child.wait is never called.
Throws an error if the child process cannot be started, for example because the command does not exist or is not executable, or because the working directory does not exist. A command, argument, working directory or environment entry that contains a NUL character is an error as well.
On POSIX platforms, the child process starts with the default action for every signal and with no
signal blocked, even if the parent process ignores or blocks signals. For example, the child of a
program that runs under nohup does not ignore SIGHUP.
On Windows, the child process is terminated when the parent process exits.
If the child process's standard input is a pipe, use IO.Process.Child.takeStdin to make it
possible to close the child's standard input before the process terminates, which provides the child with an end-of-file marker.
Asynchronous Subprocesses
This program uses the Unix utility grep as a filter to find four-digit palindromes.
It feeds all numbers from 0 through 9999 to the grep process and then reads its result.
This code is only correct when grep is sufficiently fast and when the output pipe is large enough to contain all 90 four-digit palindromes.
def main : IO Unit := do
let grep ← IO.Process.spawn {
cmd := "grep",
args := #[r#"^\([0-9]\)\([0-9]\)\2\1$"#],
stdin := .piped,
stdout := .piped,
stderr := .null
}
-- Feed the input to the subprocess
for i in [0:10000] do
grep.stdin.putStrLn (toString i)
-- Consume its output, after waiting 100ms for grep to process the data.
IO.sleep 100
let count := (← grep.stdout.readToEnd).trimAscii.split "\n" |>.length
IO.println s!"There are {count} four-digit palindromes."
Its output is:
stdoutThere are 90 four-digit palindromes.Configuration for a child process to be spawned.
Use IO.Process.spawn to start the child process. IO.Process.output and IO.Process.run can be
used when the child process should be run to completion, with its output and/or error code captured.
Constructor
IO.Process.SpawnArgs.mk
Extends
Fields
stdin : IO.Process.Stdio
stdout : IO.Process.Stdio
stderr : IO.Process.Stdio
cmd : String
The command to run.
A command without a directory separator is searched for in the directories of the PATH variable
of the child process's environment. Any other relative path is relative to the child process's
working directory.
On POSIX platforms, an executable file that the system cannot run directly, such as a script
without a #! line, is run by /bin/sh.
On Windows, a command without a directory is first searched for where the system looks for
executables: in the directory of the current executable, the current working directory, the
system directories and the directories of the current process's PATH, in this order and with the
extension .exe if the command has none. Only if it is not found there, the child process's
working directory and the directories of its PATH are searched, also trying the extensions
.com and .exe.
args : Array String
Arguments for the command, which the child process receives unchanged.
On Windows, where a process receives a single command line, the arguments are quoted as needed
according to the conventions of the Microsoft C runtime. Programs that split their command line
differently, such as cmd.exe, may see other arguments, and programs built on the Cygwin or
MSYS2 runtime expand wildcards and braces in arguments that did not need quotes.
In particular, a batch file (.bat or .cmd) is run by cmd.exe, which does not understand
this quoting: an argument containing " can end the quoted section, so that characters such as
& and | in it run further commands, and % expands variables even inside quotes. Untrusted
arguments must not be passed to a batch file.
cwd : Option System.FilePath
The child process's working directory. Inherited from the parent current process if none.
env : Array (String × Option String)
Add or remove environment variables for the child process.
The child process inherits the parent's environment, as modified by env. Keys in the array are
the names of environment variables. A none, causes the entry to be removed from the environment,
and some sets the variable to the new value, adding it if necessary. Variables are processed from left to right.
On Windows, the names of environment variables are not case-sensitive. Moreover, the child process
receives the parent's values of HOMEDRIVE, HOMEPATH, LOGONSERVER, PATH, SYSTEMDRIVE,
SYSTEMROOT, TEMP, USERDOMAIN, USERNAME, USERPROFILE and WINDIR unless env sets
them, even if env removes them or inheritEnv is false.
inheritEnv : Bool
Inherit environment variables from the spawning process. On Windows, some variables are inherited
in any case; see env.
setsid : Bool
Starts the child process in a new session and process group using setsid.
This has no effect on Windows, where the closest equivalent would also detach the child process from the console.
Configuration for the standard input, output, and error handles of a child process.
Constructor
IO.Process.StdioConfig.mk
Fields
stdin : IO.Process.Stdio
Configuration for the process' stdin handle.
A child process that inherits standard input can consume input meant for the parent or wait for
input from the terminal. Use .null for a child that is not supposed to read from the terminal.
stdout : IO.Process.Stdio
Configuration for the process' stdout handle.
stderr : IO.Process.Stdio
Configuration for the process' stderr handle.
Whether the standard input, output, and error handles of a child process should be attached to pipes, inherited from the parent, or null.
If the stream is a pipe, then the parent process can use it to communicate with the child.
Constructors
IO.Process.Stdio.piped : IO.Process.Stdio
The stream should be attached to a pipe. The pipe carries bytes unchanged on all platforms; in particular, line endings are not translated on Windows.
IO.Process.Stdio.inherit : IO.Process.Stdio
The stream should be inherited from the parent process. On POSIX platforms, a parent process that was started with that stream closed passes on the null device.
IO.Process.Stdio.null : IO.Process.Stdio
The stream should be empty.
The type of handles that can be used to communicate with a child process on its standard input, output, or error streams.
For IO.Process.Stdio.piped, this type is IO.FS.Handle. Otherwise, it is Unit, because no
communication is possible.
A child process that was spawned with configuration cfg.
The configuration determines whether the child process's standard input, standard output, and
standard error are IO.FS.Handles or Unit.
Fields
stdin : cfg.stdin.toHandleType
The child process's standard input handle, if it was configured as IO.Process.Stdio.piped, or
() otherwise.
stdout : cfg.stdout.toHandleType
The child process's standard output handle, if it was configured as IO.Process.Stdio.piped, or
() otherwise.
stderr : cfg.stderr.toHandleType
The child process's standard error handle, if it was configured as IO.Process.Stdio.piped, or
() otherwise.
Blocks until the child process has exited and returns its exit code. It can be called any number of times, also from several threads at once. On POSIX platforms, the exit code of a child process that was terminated by a signal is 128 plus the number of the signal.
Throws an error instead of blocking forever if it is called on the thread of the event loop before
the child process is known to have exited, because that thread is the one that detects the exit. A
task with sync := true runs on that thread if the task that it depends on is completed by the
event loop, for example by a timer or a socket.
On POSIX platforms, if other code in the same process reaps the child, for example a C library
calling waitpid(-1, …), this function never returns.
Checks whether the child has exited. Returns none if the process has not exited, or its exit code
if it has.
The exit of a child process is detected on the thread of the event loop, so tryWait keeps
returning none for as long as its caller occupies that thread; see IO.Process.Child.wait.
IO.Process.Child.kill {cfg : IO.Process.StdioConfig} (child : IO.Process.Child cfg) (force : Bool := true) : IO UnitIO.Process.Child.kill {cfg : IO.Process.StdioConfig} (child : IO.Process.Child cfg) (force : Bool := true) : IO Unit
Terminates the child process by sending it the SIGKILL signal, or SIGTERM if force is false.
Does nothing if the child process has already exited.
SIGKILL ends the process immediately. SIGTERM gives the process the chance to handle the signal,
for example to clean up before exiting, or to ignore it.
If the process was started using SpawnArgs.setsid, the signal is sent to the entire process group
instead, including any members that remain after the child process has exited. Once all members of
the group have exited, the system may give its identifier to a new process group, which a later
call would signal instead.
On Windows, the process is always terminated immediately using TerminateProcess, and force has
no effect.
IO.Process.Child.takeStdin {cfg : IO.Process.StdioConfig} : IO.Process.Child cfg → IO (cfg.stdin.toHandleType × IO.Process.Child { stdin := IO.Process.Stdio.null, stdout := cfg.stdout, stderr := cfg.stderr })IO.Process.Child.takeStdin {cfg : IO.Process.StdioConfig} : IO.Process.Child cfg → IO (cfg.stdin.toHandleType × IO.Process.Child { stdin := IO.Process.Stdio.null, stdout := cfg.stdout, stderr := cfg.stderr })
Extracts the stdin field from a Child object, allowing the handle to be closed while maintaining
a reference to the child process.
File handles are closed when the last reference to them is dropped. Closing the child's standard
input causes an end-of-file marker. Because the Child object has a reference to the standard
input, this operation is necessary in order to close the stream while the process is running (e.g.
to extract its exit code after calling Child.wait). Many processes do not terminate until their
standard input is exhausted.
Closing a Subprocess's Standard Input
This program uses the Unix utility grep as a filter to find four-digit palindromes, ensuring that the subprocess terminates successfully.
It feeds all numbers from 0 through 9999 to the grep process, then closes the process's standard input, which causes it to terminate.
After checking grep's exit code, the program extracts its result.
def main : IO UInt32 := do
let grep ← do
let (stdin, child) ← (← IO.Process.spawn {
cmd := "grep",
args := #[r#"^\([0-9]\)\([0-9]\)\2\1$"#],
stdin := .piped,
stdout := .piped,
stderr := .null
}).takeStdin
-- Feed the input to the subprocess
for i in [0:10000] do
stdin.putStrLn (toString i)
-- Return the child without its stdin handle.
-- This closes the handle, because there are
-- no more references to it.
pure child
-- Wait for grep to terminate
if (← grep.wait) != 0 then
IO.eprintln s!"grep terminated unsuccessfully"
return 1
-- Consume its output
let count := (← grep.stdout.readToEnd).trimAscii.split "\n" |>.length
IO.println s!"There are {count} four-digit palindromes."
return 0
Its output is:
stdoutThere are 90 four-digit palindromes.