Standard library · System and tools

os.process

Running other programs, talking to them through pipes, reading with a time limit, telling an exit code from a signal, and stopping them.

import os.process

The os.process package runs another program directly, with no shell in between. The program's path and its arguments are given separately, so nothing has to be quoted and spaces or special characters in an argument cause no trouble. Use it to call tools such as git, ffmpeg or a compiler with file names that came from a user. For a quick one-line shell command use os (Run, RunCapture) or os.shell; when a program cannot start at all, the reason is recorded in os.error.

A run has up to four steps: Start or StartCaptured launches the program and returns at once, Wait blocks until it exits and returns the exit code, ReadStdout and ReadStderr read what a captured run printed, and Cleanup deletes the two temporary files that held it. A captured program gets an empty standard input.

For a program you talk to while it runs, with pipes, time limits and exit codes or signals, use Command, Launch and Child, described in the sections below. For a program that must see a terminal, use os.pty.

What people get wrong:

  • Treating IsRunning as a live check. It reports a flag that Start sets and only Wait, Kill or Terminate clear; it stays true after the program has exited on its own.
  • Killing without waiting. Kill and Terminate only send the signal. Call Wait afterwards, or the finished process stays in the process table as a zombie.
  • Expecting a timeout from Wait. Wait on a Process waits as long as the program runs. To give up after a while use a Child (see below), whose Wait takes a time limit.
  • Forgetting Cleanup. Each captured run leaves two files in the temporary folder until you call it.

On Windows the arguments are joined into one command line with quotes around those that contain spaces, and the ANSI CreateProcessA starts the program. An argument that itself contains a ", or text outside the system code page such as Persian, does not arrive intact there; Fork and WaitPid return -1.

Pass arguments exactly as they are

Each element of the argument vector reaches the program as one argument, byte for byte. Spaces, quotes, a $ or a ; mean nothing special, because no shell reads them. That makes this package the safe way to pass file names and other text that came from a user.

os-process-guide-args.salam
import os.process

func main:
    mut args := Vector {} as Vector<str>
    defer args.Free()
    args.Push("[%s]\n")
    args.Push("two words")
    args.Push("it's quoted")
    args.Push("$HOME")
    args.Push("*.txt; rm -rf x")
    mut p := process.StartCaptured("printf", args)
    process.Wait(p)
    print process.ReadStdout(p)
    process.Cleanup(p)
end
Output[two words] [it's quoted] [$HOME] [*.txt; rm -rf x]

The program name is looked up on the PATH like in a terminal, so printf works without a full path. The vector does not include the program name itself; the package adds it. This exactness holds on Linux and macOS; see the note above for Windows.

Exit code, output and error output

A program reports success with exit code zero and anything else on failure, and it writes its complaints to the error output. After Wait, read both: ReadStdout for the results and ReadStderr for the reason it failed. Call Cleanup after reading, because the captured output is kept in temporary files until then.

os-process-guide-exitcode.salam
import os.process

func main:
    mut args := Vector {} as Vector<str>
    defer args.Free()
    args.Push("-c")
    args.Push("echo copying files; echo disk is full >&2; exit 3")
    mut p := process.StartCaptured("sh", args)
    code := process.Wait(p)
    out := process.ReadStdout(p).Trim()
    err := process.ReadStderr(p).Trim()
    process.Cleanup(p)
    println "output:", out
    if code != 0:
        println "failed with code", code, "and said:", err
        ret 0
    end
    println "all good"
end
Outputoutput: copying files failed with code 3 and said: disk is full

Run several programs at once

StartCaptured returns as soon as the program has started, so you can start several and wait for them afterwards. The total time is about that of the slowest one rather than the sum of all. Waiting in the order you started them keeps the output in a fixed order, even when a later job finished first.

os-process-guide-parallel.salam
import os.process

func job(name: str, seconds: str): process.Process:
    mut args := Vector {} as Vector<str>
    defer args.Free()
    args.Push("-c")
    args.Push("sleep " + seconds + "; echo " + name + " done")
    ret process.StartCaptured("sh", args)
end

func main:
    mut jobs := Vector {} as Vector<process.Process>
    defer jobs.Free()
    jobs.Push(job("thumbnails", "0.3"))
    jobs.Push(job("search index", "0.1"))
    jobs.Push(job("sitemap", "0.2"))
    println "started", jobs.Len(), "jobs"
    repeat jobs.Len() in i:
        mut p := jobs.Get(i)
        code := process.Wait(p)
        println code, process.ReadStdout(p).Trim()
        process.Cleanup(p)
    end
end
Outputstarted 3 jobs 0 thumbnails done 0 search index done 0 sitemap done

Keep the number of programs you run at once reasonable; os.platform's CpuCount is a good limit for work that keeps the processor busy.

A helper that runs a program and returns its output

Most programs need the same few lines every time: start, check that it started, wait, read, clean up. Put them in one function. A defer right after the start makes sure Cleanup runs on every way out of the function, and an out-parameter tells the caller whether the program succeeded.

os-process-guide-helper.salam
import os.error
import os.process

func capture(program: str, args: Vector<str>, ok &: bool): str:
    error.Clear()
    mut p := process.StartCaptured(program, args)
    if error.HasError():
        ok = false
        ret ""
    end
    defer process.Cleanup(p)
    ok = process.Wait(p) == 0
    ret process.ReadStdout(p)
end

func main:
    mut args := Vector {} as Vector<str>
    defer args.Free()
    args.Push("-c")
    args.Push("printf 'pear\\napple\\nfig\\n' | sort")
    mut ok := false
    out := capture("sh", args, ok)
    println "worked:", ok
    print out
    capture("/no/such/tool", args, ok)
    println "missing tool worked:", ok
end
Outputworked: true apple fig pear missing tool worked: false

Stop a program

Terminate sends SIGTERM, which a well-behaved program catches to save its work and exit; Kill sends SIGKILL, which cannot be caught. Either way, Wait collects the program afterwards. A program ended by a signal reports 128 plus the signal number as its exit code, so 143 means SIGTERM and 137 means SIGKILL, the same numbers a shell shows.

os-process-guide-stop.salam
import os.process

func main:
    mut args := Vector {} as Vector<str>
    defer args.Free()
    args.Push("30")
    mut worker := process.Start("sleep", args)
    println "started, running:", process.IsRunning(worker)
    if process.Terminate(worker) != 0:
        println "could not signal it"
        ret 1
    end
    code := process.Wait(worker)
    println "stopped with exit code", code, "= 128 + signal", code - 128
    println "running:", process.IsRunning(worker)
    ret 0
end
Outputstarted, running: true stopped with exit code 143 = 128 + signal 15 running: false

Talk to a running child

Start and StartCaptured run a program to the end. When you need to talk to it while it runs, describe it with a Command (NewCommand gives one for a program), pass it to Launch, and use the Child it returns. Set stdin_mode, stdout_mode and stderr_mode to Pipe (or call Piped) to connect a stream to your program, to Null to throw it away, or leave Inherit to share your own. Merge on the error stream puts it into the output pipe in the order it was written. Arg, Env, Unset and the cwd and clear_env fields set the arguments, the environment and the folder. Writing to a child that has already gone returns false and never kills your program.

os-process-guide-launch.salam
import os.process

func main:
    mut cmd := process.NewCommand("sh")
    cmd.Arg("-c")
    cmd.Arg("read name; echo hello $name")
    cmd.stdin_mode = process.Pipe
    cmd.stdout_mode = process.Pipe
    mut child := process.Launch(cmd)
    if not child.ok:
        println "could not start:", child.error
        ret 1
    end
    child.Write("Sara\n")
    reply := child.ReadLine(2000)
    println reply.data
    reply.Free()
    println "exit code:", child.Wait(2000).code
    child.Close()
    cmd.Free()
end
Outputhello Sara exit code: 0

Read with a time limit

Every read takes a time in milliseconds: 0 only looks, a positive number waits that long, a negative number waits for ever. ReadAvailable returns whatever has arrived, ReadLine one complete line, Read an exact number of bytes, ReadUntil everything up to a given text (the way to wait for a prompt) and ReadFor everything that arrives in a period. A read returns a Chunk: check timed_out (nothing came, and the child may still be working) and eof (the stream ended) before using data, and Free it. Bytes that were read but not yet returned stay in the child, so a timed-out call loses nothing. The ReadErr methods do the same for the error pipe, and ReadBytes reads binary data into a buffer.

os-process-guide-read.salam
import os.process

func main:
    mut cmd := process.NewCommand("sh")
    cmd.Arg("-c")
    cmd.Arg("echo first; sleep 0.3; echo second")
    cmd.stdout_mode = process.Pipe
    mut child := process.Launch(cmd)
    a := child.ReadLine(2000)
    println "line:", a.data
    b := child.ReadLine(50)
    println "nothing yet:", b.timed_out
    c := child.ReadLine(2000)
    println "line:", c.data
    d := child.ReadLine(2000)
    println "closed:", d.eof
    a.Free()
    b.Free()
    c.Free()
    d.Free()
    _status := child.Wait(2000)
    child.Close()
    cmd.Free()
end
Outputline: first nothing yet: true line: second closed: true

Exit code or signal

Child.Wait takes a time limit and returns a Status. A child that ended by itself has exited set and its code in code; one that a signal ended has signaled set and the number in signal. This differs from Process.Wait, which folds a signal into 128 plus the number. ReturnCode gives the Python-style number (the code, or the negative signal), and Success is true for code 0. When the limit passes first, timed_out is set and the child keeps running; Poll asks whether it is still running without waiting.

os-process-guide-status.salam
import os.process

func describe(script: str):
    mut cmd := process.NewCommand("sh")
    cmd.Arg("-c")
    cmd.Arg(script)
    mut child := process.Launch(cmd)
    st := child.Wait(2000)
    if st.exited:
        println "exited with code", st.code
    else st.signaled:
        println "killed by signal", st.signal
    end
    child.Close()
    cmd.Free()
end

func main:
    describe("exit 3")
    describe("kill -TERM $$")
    describe("kill -KILL $$")
end
Outputexited with code 3 killed by signal 15 killed by signal 9

Run with a timeout

RunTimeout is the one-call version: it writes the input text, collects the whole output and error output, and kills the child when the time runs out. It reads both pipes while it writes, so a child that prints a megabyte on each stream cannot deadlock it. RunCommand does the same for a Command with an environment or folder. The result is a RunResult: started, status, stdout, stderr and timed_out; call Free on it.

os-process-guide-timeout.salam
import os.process

func main:
    mut args := Vector {} as Vector<str>
    defer args.Free()
    args.Push("-c")
    args.Push("cat; echo done")
    mut ok := process.RunTimeout("sh", args, "from stdin\n", 2000)
    print ok.stdout
    println "timed out:", ok.timed_out
    ok.Free()

    mut hang_args := Vector {} as Vector<str>
    defer hang_args.Free()
    hang_args.Push("-c")
    hang_args.Push("sleep 30")
    mut hang := process.RunTimeout("sh", hang_args, "", 200)
    println "timed out:", hang.timed_out, "return code:", hang.status.ReturnCode()
    hang.Free()
end
Outputfrom stdin done timed out: false timed out: true return code: -9

Stop a child and everything it started

Kill a shell and the programs it started keep running. Start the child with new_group and KillGroup (or SignalGroup with any signal) stops the whole group. RunTimeout does this for you. Signal, Kill and Terminate reach only the child itself.

os-process-guide-group.salam
import os.process

func main:
    mut cmd := process.NewCommand("sh")
    cmd.Arg("-c")
    cmd.Arg("sleep 30 & sleep 30 & wait")
    cmd.new_group = true
    cmd.stdout_mode = process.Pipe
    mut child := process.Launch(cmd)
    println "group killed:", child.KillGroup()
    st := child.Wait(2000)
    println "signal:", st.signal
    tail := child.ReadAvailable(2000)
    println "pipe closed:", tail.eof
    tail.Free()
    child.Close()
    cmd.Free()
end
Outputgroup killed: true signal: 9 pipe closed: true

On Unix a program that cannot be found, or a folder that cannot be entered, makes Launch return a child whose ok is false and whose error says why; the check happens before Launch returns, so there is no need to wait for an exit code 127.

On Windows Launch uses CreateProcessW and anonymous pipes. Every signal ends the child at once and is reported as a signal, RunCommand writes all of its input before it starts reading, and the pseudo terminal of os.pty is not available. The tests that start real children run on Linux and macOS.

NeedUse
Run a program and see its output on the screenStart, then Wait
Run a program and use its outputStartCaptured, Wait, ReadStdout, Cleanup
Stop a program politely, or at onceTerminate, Kill
Pipes or redirectionrun sh with -c and a script, as in the examples above
A one-line command and its resultos.shell
Talk to a program while it runsNewCommand, Launch, then Write and the Read methods
Wait for a prompt or a line, with a time limitReadUntil, ReadLine
Tell an exit code from a signalChild.Wait and its Status
Run, capture everything, give up after a timeRunTimeout
Stop a program and everything it startednew_group and KillGroup
A program that needs a terminalos.pty

Types

Command

struct Command
How to start a child: the program, its arguments, folder, environment and what to do with its three streams. Fill it in, pass it to Launch, and call Free when done.
NameTypeDescription
programstr = ""The program to run. A name without a slash is searched on PATH.
argsVectorThe arguments, not including the program name. Each reaches the child as one argument.
cwdstr = ""The folder to run in. Empty means your own current folder.
envHashMapVariables to add to the child's environment, replacing any with the same name.
unset_envVectorNames of variables to remove from the child's environment.
clear_envbool = falseWhen true the child starts with an empty environment plus only the variables in env.
stdin_modeint = 0What to do with the child's input: Inherit, Pipe or Null.
stdout_modeint = 0What to do with the child's output: Inherit, Pipe or Null.
stderr_modeint = 0What to do with the child's error output: Inherit, Pipe, Null or Merge.
new_groupbool = falseStarts the child in its own process group, so KillGroup can stop it together with everything it started. Unix only; on Windows it adds a new console process group.
os-process-Command.salam
import os.process

func main:
    mut cmd := process.NewCommand("sh")
    cmd.Arg("-c")
    cmd.Arg("echo $GREETING from $(pwd); echo trouble 1>&2")
    cmd.Env("GREETING", "salam")
    cmd.cwd = "/"
    cmd.stdout_mode = process.Pipe
    cmd.stderr_mode = process.Merge
    mut child := process.Launch(cmd)
    all := child.ReadFor(2000)
    print all.data
    all.Free()
    println "exit:", child.Wait(2000).code
    child.Close()
    cmd.Free()
end
Outputsalam from / trouble exit: 0

Arg

func Arg(a: str)
Adds one argument.

The example for this item is shown with the ones above: os-process-Command.salam

Env

func Env(name: str, value: str)
Sets one environment variable for the child.

The example for this item is shown with the ones above: os-process-Command.salam

Unset

func Unset(name: str)
Removes one variable from the child's environment.

The example for this item is shown with the ones above: os-process-Command.salam

Piped

func Piped()
Sets all three streams to Pipe.
os-process-Launch.salam
import os.process

func main:
    mut cmd := process.NewCommand("cat")
    cmd.Piped()
    mut child := process.Launch(cmd)
    child.Write("hello child\n")
    line := child.ReadLine(2000)
    println "got:", line.data
    line.Free()
    child.CloseStdin()
    status := child.Wait(2000)
    println "exit code:", status.code
    child.Close()
    cmd.Free()
end
Outputgot: hello child exit code: 0

Free

func Free()
Frees the argument list and the environment maps. Call it once you no longer launch from this command.

The example for this item is shown with the ones above: os-process-Launch.salam

Status

struct Status
How a child ended: it exited with a code, or a signal ended it, or you stopped waiting.
NameTypeDescription
exitedbool = falseTrue when the child ended by itself and code holds its exit code.
codeint = 0The exit code, valid when exited is true.
signaledbool = falseTrue when a signal ended the child and signal holds its number.
signalint = 0The number of the signal that ended the child, valid when signaled is true.
timed_outbool = falseTrue when a wait gave up before the child ended; the child is then still running.
os-process-Signal.salam
import os.process

func main:
    mut cmd := process.NewCommand("sleep")
    cmd.Arg("30")
    mut child := process.Launch(cmd)
    println "running:", child.Poll()
    println "sent:", child.Terminate()
    status := child.Wait(2000)
    println "signaled:", status.signaled, "signal:", status.signal
    println "return code:", status.ReturnCode()
    println "running:", child.Poll()
    child.Close()
    cmd.Free()
end
Outputrunning: true sent: true signaled: true signal: 15 return code: -15 running: false

Success

func Success(): bool
True when the child exited with code 0.
os-process-Read.salam
import os.process

func main:
    mut cmd := process.NewCommand("sh")
    cmd.Arg("-c")
    cmd.Arg("printf 'abcdef'; sleep 0.2; printf 'ghi:tail\\n'")
    cmd.stdout_mode = process.Pipe
    mut child := process.Launch(cmd)
    first := child.Read(4, 2000)
    println "four bytes:", first.data
    upto := child.ReadUntil(":", 2000)
    println "up to the colon:", upto.data
    rest := child.ReadLine(2000)
    println "rest of the line:", rest.data
    end_of := child.ReadAvailable(2000)
    println "ended:", end_of.eof
    first.Free()
    upto.Free()
    rest.Free()
    end_of.Free()
    status := child.Wait(2000)
    println "success:", status.Success()
    child.Close()
    cmd.Free()
end
Outputfour bytes: abcd up to the colon: efghi: rest of the line: tail ended: true success: true

ReturnCode

func ReturnCode(): int
The code as a shell or Python shows it: the exit code, or the negative signal number when a signal ended the child.

The example for this item is shown with the ones above: os-process-Signal.salam

Chunk

struct Chunk
What a read returns: the text, how many bytes it holds, and whether the stream ended or nothing came in time.
NameTypeDescription
datastr = ""The text read, as a string that stops at the first zero byte. Use len for the real byte count. Empty (but still yours to free) on a timeout or at the end.
lenint = 0The number of bytes read. For a line it excludes the line ending.
eofbool = falseTrue when the stream has ended and no more data will come.
timed_outbool = falseTrue when nothing arrived within the time allowed. Whatever was partly read stays buffered for the next call.

The example for this item is shown with the ones above: os-process-Read.salam

Free

func Free()
Frees the text. Every chunk a read returns must be freed.

The example for this item is shown with the ones above: os-process-Launch.salam

RunResult

struct RunResult
Everything RunTimeout collected: whether the child started, how it ended and all of its output and error output.
NameTypeDescription
startedbool = falseFalse when the program could not be started; the other fields are then empty.
statusStatusHow the child ended. After a timeout it is the kill signal with timed_out set.
stdoutstr = ""All the output, as a string that stops at the first zero byte.
stderrstr = ""All the error output.
timed_outbool = falseTrue when the time ran out and the child was killed.
os-process-RunTimeout.salam
import os.process

func main:
    mut args := Vector {} as Vector<str>
    defer args.Free()
    args.Push("-c")
    args.Push("echo fast output; echo warning 1>&2; exit 2")
    mut quick := process.RunTimeout("sh", args, "", 2000)
    println "code:", quick.status.code
    print "stdout:", quick.stdout
    print "stderr:", quick.stderr
    quick.Free()

    mut slow_args := Vector {} as Vector<str>
    defer slow_args.Free()
    slow_args.Push("-c")
    slow_args.Push("echo started; sleep 30")
    mut slow := process.RunTimeout("sh", slow_args, "", 300)
    println "timed out:", slow.timed_out, "signal:", slow.status.signal
    print "partial:", slow.stdout
    slow.Free()
end
Outputcode: 2 stdout: fast output stderr: warning timed out: true signal: 9 partial: started

Free

func Free()
Frees the two output strings.

The example for this item is shown with the ones above: os-process-RunTimeout.salam

Child

struct Child
A running or finished child process with its pipes. Get one from Launch; call Close when you are done with it.
NameTypeDescription
pidint = 0The process id.
okbool = falseTrue when the child started. When false, error says why.
errorstr = ""Why the child could not start, or empty.
finishedbool = falseTrue once a wait or a poll has seen the child end; status then holds the result.
statusStatusHow the child ended, valid once finished is true.
h_ini64 = -1The write end of the child's input pipe, or -1. Low level; the methods use it for you.
h_outi64 = -1The read end of the child's output pipe, or -1. On a terminal from os.pty this is the terminal itself.
h_erri64 = -1The read end of the child's error pipe, or -1.
h_proci64 = -1The process handle on Windows, or -1.
sent_signalint = 0The last signal sent with Signal; Windows uses it to report a kill as a signal.
out_buffdio.BufBytes read from the output pipe but not yet returned.
err_buffdio.BufBytes read from the error pipe but not yet returned.

The example for this item is shown with the ones above: os-process-Launch.salam

Write

func Write(text: str): bool
Writes the whole text to the child's input. False when the input is closed or the child is gone; a write to a dead child does not kill your program.

The example for this item is shown with the ones above: os-process-Launch.salam

WriteBytes

func WriteBytes(data: void*, n: int): bool
Writes bytes from a pointer, for binary data that may contain zero bytes.

The example for this item is shown with the ones above: os-process-Launch.salam

CloseStdin

func CloseStdin()
Closes the child's input so a program such as cat sees the end of its input. On a terminal it sends Ctrl-D instead.

The example for this item is shown with the ones above: os-process-Launch.salam

ReadAvailable

func ReadAvailable(ms: int): Chunk
Returns whatever has arrived, waiting up to ms milliseconds for the first bytes. 0 only checks; a negative number waits for ever.

The example for this item is shown with the ones above: os-process-Read.salam

ReadLine

func ReadLine(ms: int): Chunk
Reads one line, without its line ending, waiting up to ms milliseconds for it to be complete. At the end of the stream it returns what is left with eof set.

The example for this item is shown with the ones above: os-process-Read.salam

Read

func Read(n: int, ms: int): Chunk
Reads exactly n bytes, waiting up to ms milliseconds in all. At the end of the stream it returns the fewer that were left with eof set.

The example for this item is shown with the ones above: os-process-Read.salam

ReadUntil

func ReadUntil(text: str, ms: int): Chunk
Reads up to and including the first occurrence of the text, waiting up to ms milliseconds. This is how to wait for a prompt.

The example for this item is shown with the ones above: os-process-Read.salam

ReadFor

func ReadFor(ms: int): Chunk
Collects everything that arrives during ms milliseconds, or until the stream ends. A negative number reads to the end.

The example for this item is shown with the ones above: os-process-Command.salam

ReadBytes

func ReadBytes(dst: void*, max: int, ms: int): int
Reads up to max bytes into a buffer you own. Returns the count, 0 on a timeout and -1 at the end of the stream.

The example for this item is shown with the ones above: os-process-Launch.salam

ReadErrAvailable

func ReadErrAvailable(ms: int): Chunk
Like ReadAvailable, for the error pipe.

The example for this item is shown with the ones above: os-process-Command.salam

ReadErrLine

func ReadErrLine(ms: int): Chunk
Like ReadLine, for the error pipe.

The example for this item is shown with the ones above: os-process-Command.salam

ReadErrUntil

func ReadErrUntil(text: str, ms: int): Chunk
Like ReadUntil, for the error pipe.

The example for this item is shown with the ones above: os-process-Command.salam

ReadErrFor

func ReadErrFor(ms: int): Chunk
Like ReadFor, for the error pipe.

The example for this item is shown with the ones above: os-process-Command.salam

Wait

func Wait(ms: int): Status
Waits up to ms milliseconds for the child to end and returns its Status. On a timeout the status has timed_out set and the child keeps running. 0 only checks; a negative number waits for ever. A finished child returns the same status every time.

The example for this item is shown with the ones above: os-process-Launch.salam

Poll

func Poll(): bool
True while the child is still running. It also collects the child once it has ended.

The example for this item is shown with the ones above: os-process-Signal.salam

Signal

func Signal(sig: int): bool
Sends a signal to the child. On Windows every signal ends the child.

The example for this item is shown with the ones above: os-process-Signal.salam

Kill

func Kill(): bool
Sends SigKill. Call Wait afterwards.

The example for this item is shown with the ones above: os-process-Signal.salam

Terminate

func Terminate(): bool
Sends SigTerm, asking the child to finish.

The example for this item is shown with the ones above: os-process-Signal.salam

SignalGroup

func SignalGroup(sig: int): bool
Sends a signal to the child's whole process group. The child must have been started with new_group.

The example for this item is shown with the ones above: os-process-Signal.salam

KillGroup

func KillGroup(): bool
Kills the child and everything in its group. On Windows it stops the whole process tree.

The example for this item is shown with the ones above: os-process-Signal.salam

Close

func Close()
Closes the pipes and frees the read buffers. It does not stop the child; wait for it or kill it first.

The example for this item is shown with the ones above: os-process-Launch.salam

Process

struct Process
A process, running or finished.
NameTypeDescription
pidint = 0The process id.
handlevoid*The process handle on Windows.
runningbool = falseSet by Start and cleared by Wait, Kill and Terminate; it is not updated when the program exits on its own.
exit_codeint = 0The exit code, once Wait has returned; 128 plus the signal number when a signal ended it.
stdout_pathstr = ""The temporary file holding the captured output.
stderr_pathstr = ""The temporary file holding the captured error output.
os-process-Start.salam
import os.process

func main:
    mut args := Vector {} as Vector<str>
    defer args.Free()
    args.Push("hello from the child process")
    mut p := process.StartCaptured("/bin/echo", args)
    println process.Pid(p) > 0
    code := process.Wait(p)
    println code, process.ExitCode(p), process.IsRunning(p)
    print process.ReadStdout(p)
    println "[" + process.ReadStderr(p) + "]"
    process.Cleanup(p)
end
Outputtrue 0 0 false hello from the child process []

SpawnOptions

struct SpawnOptions
How to start a program with Spawn.
NameTypeDescription
pathstr = ""The program.
argsVectorIts arguments.
raw_argsstr = ""Windows only: text added to the command line as it is.
cwdstr = ""The folder to run in.
outputstr = ""A file that receives standard output and standard error.

The example for this item is shown with the ones above: os-process-Start.salam

Constants and variables

Inherit

const Inherit: i32 = 0
Stream mode: the child shares your own input, output or error stream. This is the default.

The example for this item is shown with the ones above: os-process-Command.salam

Pipe

const Pipe: i32 = 1
Stream mode: a pipe connects you to the child. Write to its input with Write; read its output with the Read methods.

The example for this item is shown with the ones above: os-process-Launch.salam

Null

const Null: i32 = 2
Stream mode: the stream is connected to the empty device. Reading from it gives end of file and writing to it discards the data.

The example for this item is shown with the ones above: os-process-Command.salam

Merge

const Merge: i32 = 3
Stream mode for the error stream only: the child's error output goes into the same pipe as its output, in the order it was written.

The example for this item is shown with the ones above: os-process-Command.salam

SigHup

const SigHup: i32 = 1
The hang-up signal, 1.

The example for this item is shown with the ones above: os-process-Signal.salam

SigInt

const SigInt: i32 = 2
The interrupt signal, 2, the one Ctrl-C sends.

The example for this item is shown with the ones above: os-process-Signal.salam

SigQuit

const SigQuit: i32 = 3
The quit signal, 3.

The example for this item is shown with the ones above: os-process-Signal.salam

SigKill

const SigKill: i32 = 9
The kill signal, 9. It cannot be caught.

The example for this item is shown with the ones above: os-process-Signal.salam

SigTerm

const SigTerm: i32 = 15
The terminate signal, 15, a polite request to finish.

The example for this item is shown with the ones above: os-process-Signal.salam

Functions

Launch

func Launch(c: Command): Child
Starts a child as the command describes and returns at once. Check ok; when it is false, error and os.error say why.

The example for this item is shown with the ones above: os-process-Launch.salam

NewCommand

func NewCommand(program: str): Command
A command for a program, with every stream inherited and no arguments yet.

The example for this item is shown with the ones above: os-process-Launch.salam

RunCommand

func RunCommand(c: Command, text: str, timeout_ms: int): RunResult
Runs a command to the end: writes the text to its input, collects all of its output and error output without ever blocking on a full pipe, and kills it when timeout_ms passes. A negative time means no limit.

The example for this item is shown with the ones above: os-process-Command.salam

RunTimeout

func RunTimeout(program: str, args: Vector<str>, text: str, timeout_ms: int): RunResult
Runs a program with the given arguments and input text, collects its output and error output, and kills it, and everything it started, when the time in milliseconds runs out. The result tells whether it timed out.

The example for this item is shown with the ones above: os-process-RunTimeout.salam

Start

func Start(path: str, args: Vector<str>): Process
Runs a program with its arguments and does not wait; its output goes straight to your own program's output. The name is searched on PATH. When it cannot start, pid is 0 and os.error holds ProcessFailed.

The example for this item is shown with the ones above: os-process-Start.salam

StartCaptured

func StartCaptured(path: str, args: Vector<str>): Process
Like Start, but sends the program's output and error output to two temporary files for you to read after Wait, and gives it an empty standard input.

The example for this item is shown with the ones above: os-process-Start.salam

WaitPid

func WaitPid(pid: int): int
Waits for the process with this id to finish and returns its exit code, or -1. Unix only; on Windows it returns -1.
os-process-Kill.salam
import os.process

func main:
    mut args := Vector {} as Vector<str>
    defer args.Free()
    args.Push("30")
    mut p := process.Start("/bin/sleep", args)
    println process.IsRunning(p)
    process.Terminate(p)
    process.Wait(p)
    println process.IsRunning(p)
    mut p2 := process.Start("/bin/sleep", args)
    process.Kill(p2)
    process.WaitPid(process.Pid(p2))
    println "both have stopped"
end
Outputtrue false both have stopped

Wait

func Wait(p &: Process): int
Waits for the process to finish and returns its exit code: 128 plus the signal number when a signal ended it, -1 when it never started. There is no timeout.

The example for this item is shown with the ones above: os-process-Start.salam

Fork

func Fork(): int
Splits the current process in two: it returns zero in the child and the child's id in the parent. On Unix systems only; its example is not run here.
os-process-Fork.salam
import os.process

func main:
    pid := process.Fork()
    if pid == 0:
        println "I am the child"
        process.ExitNow(0)
    end
    process.WaitPid(pid)
    println "the child has finished"
end

ExitNow

func ExitNow(code: int)
Ends the process immediately with no cleanup at all, for finishing a child after Fork.

The example for this item is shown with the ones above: os-process-Fork.salam

Kill

func Kill(p &: Process): int
Kills the process at once (SIGKILL); 0 when the signal was sent. Call Wait afterwards to collect it.

The example for this item is shown with the ones above: os-process-Kill.salam

Terminate

func Terminate(p &: Process): int
Asks the process to finish gracefully (SIGTERM) so it has a chance to clean up; call Wait afterwards. On Windows it is the same as Kill.

The example for this item is shown with the ones above: os-process-Kill.salam

ReadStdout

func ReadStdout(p: Process): str
Reads the captured output once the process has finished; empty for a process started with Start. The text stops at the first zero byte.

The example for this item is shown with the ones above: os-process-Start.salam

ReadStderr

func ReadStderr(p: Process): str
Reads the captured error output; empty for a process started with Start.

The example for this item is shown with the ones above: os-process-Start.salam

Cleanup

func Cleanup(p &: Process)
Removes the temporary capture files. Read the output first; call it once per StartCaptured.

The example for this item is shown with the ones above: os-process-Start.salam

Close

func Close(p &: Process)

ExitCode

func ExitCode(p: Process): int
The process's exit code.

The example for this item is shown with the ones above: os-process-Start.salam

Pid

func Pid(p: Process): int
The process id.

The example for this item is shown with the ones above: os-process-Start.salam

IsRunning

func IsRunning(p: Process): bool
The running flag: true from Start until Wait, Kill or Terminate. It does not ask the system, so it stays true after the program exits by itself.

The example for this item is shown with the ones above: os-process-Start.salam

Spawn

func Spawn(o: SpawnOptions): Process
Starts a program in its own process group, with no console window on Windows. Failing to find the program shows up as exit code 127 on Unix.

The example for this item is shown with the ones above: os-process-Start.salam

TryWait

func TryWait(p &: Process): bool
True once the program has ended, then exit_code is set. It never blocks.

The example for this item is shown with the ones above: os-process-Start.salam

KillTree

func KillTree(p &: Process)
Kills the program and everything it started.

The example for this item is shown with the ones above: os-process-Start.salam