Skip to content

Os ​

Os holds the process: its arguments, environment, standard streams, exit, interrupts, and pipes. Cmd runs other programs.

Details ​

  • The functions that can fail, such as Os.cwd and Os.home, return a Result. The others, such as Os.args and Os.env, never fail: a missing variable is null, not an error.
  • The three streams are File.Handle values, so the File functions read and write them. They are not buffered: print, eprint, the handles, and the program's children write in the order they are called. Wrap a stream in File.buffered to write much. When the reader of standard output or standard error goes away, as | head does, the next write ends the program, whichever function made it, and the shell reports status 141.
  • Os.exit ends the process at once, and no deferred block runs, in any goroutine.
  • A program ends at the first interrupt (Ctrl-C, SIGINT, or SIGTERM where the host has it) until it calls Os.interrupt. After that call, the first interrupt makes the context done and the program finishes on its own. A second interrupt ends the run, and so does the first one after the program cancels the context itself.

Basic examples ​

Os.args gives the arguments after the program path. Os.program names the script for a usage line:

ant
let names = Os.args()
if names.isEmpty() {
  eprintln("usage: ${Path.base(Os.program())} <name>...")
  Os.exit(2)
}
for name in names {
  println("Hello, ${name}")
}
text
Hello, Ann
Hello, Bob

Os.env gives a variable's value, or null when it is not set, so ?? supplies a default:

ant
let port = Os.env("APP_NO_SUCH_PORT") ?? "8080"
println("listening on ${port}")
text
listening on 8080

Os.stdin, Os.stdout, and Os.stderr are handles:

ant
let input = Os.stdin()
while true {
  let line = try input.readLine() ?? break
  try Os.stdout().writeLine(line.toUpper())
}
try Os.stderr().writeLine("done")
text
ANT
GO

Scope ​

The streams are not buffered, so a handle's writes and println come out in the order they are called:

ant
let out = Os.stdout()
try out.writeText("one ")
print("two ")
try out.writeLine("three")
text
one two three

Os.environ gives every variable as a map:

ant
let env = Os.environ()
println(env.has("PATH"))
println(env.get("APP_NO_SUCH_VARIABLE"))
text
true
null

Os.home, Os.configDir, and Os.cacheDir return a Result: each fails when the variable it rests on is unset, or when an XDG variable holds a relative path. Keep a script's files under a directory named after the script:

ant
let config = Path.join([try Os.configDir(), "greet", "config.json"])
println(config)

Os.cwd is the working directory, an absolute path:

ant
let dir = try Os.cwd()
println(Path.isAbs(dir))
text
true

Os.uid is the effective user id, so Os.uid() == 0 asks whether the program runs as root. Os.gid is the effective group id, null where Os.uid is. On Windows both are null, and the test is false:

ant
if Os.uid() == 0 {
  eprintln("do not run as root")
}

Os.platform and Os.arch use Go's names, so macOS is "darwin":

ant
println("${Os.platform()}/${Os.arch()}")

Os.cpus is the number of CPUs the program may use at once, at least 1, so it is the limit for CPU-bound Parallel.map work:

ant
let squares = Parallel.map([1, 2, 3], func(n: int, _: Context) { n * n }, limit: Os.cpus())
println(squares)
text
[1, 4, 9]

Os.which finds the program a Cmd would start, or gives null:

ant
println(Os.which("no-such-program-ant") == null)
println(Os.which("sh") != null)
text
true
true

Os.openPipe gives two connected handles. Close the writing end, and the reading end is at end of file after what was written:

ant
let pipe = try Os.openPipe()
defer { pipe.read.close() }
try pipe.write.writeLine("through the pipe")
try pipe.write.close()
println(try pipe.read.readLine())
println(try pipe.read.readLine())
text
through the pipe
null

Os.pid is this process's id, so the program can signal itself. After a call to Os.interrupt, a SIGINT makes the context done instead of ending the run:

ant
let stop = Os.interrupt()
try Cmd.read(Cmd.new("kill", ["-INT", "${Os.pid()}"]))
stop.wait()
println("interrupted: ${stop.reason()}")
text
interrupted: interrupt

Functions by job ​

Types ​

Arguments and identity ​

  • Os.args: the arguments after the program path
  • Os.program: the program path, as the command gave it
  • Os.pid: this process's id
  • Os.uid: the effective user id, or null on Windows
  • Os.gid: the effective group id, or null on Windows

Environment ​

  • Os.env: one variable, or null when it is not set
  • Os.environ: every variable, as a map

Host and directories ​

Streams and pipes ​

Ending the process ​

  • Os.exit: end the process now with a status
  • Os.interrupt: a context done at Ctrl-C, SIGINT, or SIGTERM

Applications ​

A filter in the Unix style reads standard input and writes standard output through a buffer, which the final close writes out:

ant
let out = File.buffered(Os.stdout())
defer { out.close() }
let input = Os.stdin()
var n = 0
while true {
  let line = try input.readLine() ?? break
  n += 1
  try out.writeLine("${n}\t${line}")
}
try out.close()
text
1	apples
2	pears

Pick a command by platform rather than running uname:

ant
let opener = if Os.platform() == "darwin" { "open" } else { "xdg-open" }
try Cmd.run(Cmd.new(opener, ["report.html"]))

Read a setting from the environment and reject a bad value with a usage error:

ant
let text = Os.env("APP_NO_SUCH_WORKERS") ?? "zero"
let workers = text.toInt()
if workers == null {
  eprintln("APP_NO_SUCH_WORKERS must be a number, not ${text}")
  Os.exit(2)
}
println("${workers} workers")

Work until Ctrl-C, then finish what is in hand. Passing the context to Time.sleep ends the pause at once:

ant
let stop = Os.interrupt()
var rounds = 0
while !stop.isDone() {
  rounds += 1
  Time.sleep(10s, ctx: stop)
}
println("saving after ${rounds} round")
text
saving after 1 round

Properties and relations ​

Os.env agrees with Os.environ, and Os.interrupt gives the same context at every call:

ant
assert(Os.env("PATH") == Os.environ().get("PATH"))
assert(Os.env("APP_NO_SUCH_VARIABLE") == null)
assert(Os.interrupt() == Os.interrupt())

Possible issues ​

A directory is a Result, not a string. Use try first:

ant
let path = Path.join([Os.home(), ".greetrc"])
// error: cannot use Result[string, Error] where string is expected

Os.args leaves out the program path, so the first argument is at index 0, not 1:

ant
println(Os.args())
println(Os.args().get(1))
text
["input.txt"]
null

Os.exit runs no deferred block, so a deferred close of a buffered stream never writes it. Close the buffer before the call:

ant
let out = File.buffered(Os.stdout())
defer { out.close() }
try out.writeLine("lost")
Os.exit(1)

See also ​

Cmd · File · Path · Context · print · Os.args · Read environment variables and standard directories · Handle Ctrl-C