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 isnull, not an error. - The three streams are File.Handle values, so the
Filefunctions 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| headdoes, 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:
let names = Os.args()
if names.isEmpty() {
eprintln("usage: ${Path.base(Os.program())} <name>...")
Os.exit(2)
}
for name in names {
println("Hello, ${name}")
}Hello, Ann
Hello, BobOs.env gives a variable's value, or null when it is not set, so ?? supplies a default:
let port = Os.env("APP_NO_SUCH_PORT") ?? "8080"
println("listening on ${port}")listening on 8080Os.stdin, Os.stdout, and Os.stderr are handles:
let input = Os.stdin()
while true {
let line = try input.readLine() ?? break
try Os.stdout().writeLine(line.toUpper())
}
try Os.stderr().writeLine("done")ANT
GOScope
The streams are not buffered, so a handle's writes and println come out in the order they are called:
let out = Os.stdout()
try out.writeText("one ")
print("two ")
try out.writeLine("three")one two threeOs.environ gives every variable as a map:
let env = Os.environ()
println(env.has("PATH"))
println(env.get("APP_NO_SUCH_VARIABLE"))true
nullOs.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:
let config = Path.join([try Os.configDir(), "greet", "config.json"])
println(config)Os.cwd is the working directory, an absolute path:
let dir = try Os.cwd()
println(Path.isAbs(dir))trueOs.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:
if Os.uid() == 0 {
eprintln("do not run as root")
}Os.platform and Os.arch use Go's names, so macOS is "darwin":
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:
let squares = Parallel.map([1, 2, 3], func(n: int, _: Context) { n * n }, limit: Os.cpus())
println(squares)[1, 4, 9]Os.which finds the program a Cmd would start, or gives null:
println(Os.which("no-such-program-ant") == null)
println(Os.which("sh") != null)true
trueOs.openPipe gives two connected handles. Close the writing end, and the reading end is at end of file after what was written:
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())through the pipe
nullOs.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:
let stop = Os.interrupt()
try Cmd.read(Cmd.new("kill", ["-INT", "${Os.pid()}"]))
stop.wait()
println("interrupted: ${stop.reason()}")interrupted: interruptFunctions by job
Types
- Os.Pipe: the two handles of a pipe
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
nullon Windows - Os.gid: the effective group id, or
nullon Windows
Environment
- Os.env: one variable, or
nullwhen it is not set - Os.environ: every variable, as a map
Host and directories
- Os.platform, Os.arch: the operating system and processor, by Go's names
- Os.cpus: the CPUs the program may use at once
- Os.hostname: the host's name
- Os.cwd: the working directory
- Os.home: the user's home directory
- Os.configDir, Os.cacheDir: where programs keep configuration and what can be made again
- Os.which: the path of the program a
Cmdwould start
Streams and pipes
- Os.stdin, Os.stdout, Os.stderr: the standard streams, as handles
- Os.openPipe: two connected handles
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:
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()1 apples
2 pearsPick a command by platform rather than running uname:
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:
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:
let stop = Os.interrupt()
var rounds = 0
while !stop.isDone() {
rounds += 1
Time.sleep(10s, ctx: stop)
}
println("saving after ${rounds} round")saving after 1 roundProperties and relations
Os.env agrees with Os.environ, and Os.interrupt gives the same context at every call:
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:
let path = Path.join([Os.home(), ".greetrc"])
// error: cannot use Result[string, Error] where string is expectedOs.args leaves out the program path, so the first argument is at index 0, not 1:
println(Os.args())
println(Os.args().get(1))["input.txt"]
nullOs.exit runs no deferred block, so a deferred close of a buffered stream never writes it. Close the buffer before the call:
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
