Os.exit
func Os.exit(status: int): neverOs.exit ends the process at once with status. No deferred block runs, in any goroutine. A Unix parent sees the status modulo 256, so Os.exit(256) reads as success; a portable program exits with 0 to 125.
Details
Os.exitnever returns. Its type isnever, so a call fits wherever a value is expected, such as after??or in one branch of anif.- No deferred block runs, in the calling goroutine or any other. Clean up first, or return an
Errfrom the script, which runs deferred blocks and exits with status1. - The standard streams are not buffered, so what
print,printlnandeprintlnwrote before the call is out. AFile.bufferedhandle that is not flushed loses what its buffer holds. Panic.catchdoes not stop it.- A Unix parent sees the status modulo 256, so
Os.exit(256)reads as success andOs.exit(-1)as 255. Exit with 0 to 125 to be portable. - In
ant test, it ends the whole command with its status, and no further test runs.
Basic examples
Os.exit(2) reports a usage error after a message on standard error:
if Os.args().isEmpty() {
eprintln("usage: greet <name>")
Os.exit(2)
}
println("Hello, ${Os.args()[0]}")Nothing after the call runs:
println("start")
Os.exit(3)
println("never printed")startOs.exit(0) ends the program early with success:
if Os.args().contains("--version") {
println("greet 1.0")
Os.exit(0)
}
println("Hello")greet 1.0Scope
Because the type is never, Os.exit can supply the missing value after ??:
let name = Os.args().get(0) ?? Os.exit(2)
println("Hello, ${name}")It can also be one branch of an if expression, and the result keeps the other branch's type:
let port = if Os.args().length() == 1 { Os.args()[0] } else { Os.exit(2) }
println("listening on ${port}")listening on 8080A function that ends in Os.exit on bad input needs no value for that path:
func portOf(s: string): int {
s.toInt() ?? Os.exit(2)
}
println(portOf("80"))
println(portOf("http"))80A call in any goroutine ends the whole process, the main goroutine included:
let stop: Channel[bool] = Channel.new()
go {
println("worker exits")
Os.exit(7)
}
Channel.receive(stop)
println("never printed")worker exitsApplications
A filter in the style of grep: status 0 when some line matches, 1 when none does, and 2 for a usage error:
let word = Os.args().get(0) ?? Os.exit(2)
let text = try Os.stdin().readAll()
let hits = text.split("\n").filter({ x.contains(word) })
if hits.isEmpty() {
Os.exit(1)
}
for line in hits {
println(line)
}ant colony
ant hillThe same program with no matching line exits with 1 and prints nothing:
let word = Os.args().get(0) ?? Os.exit(2)
let text = try Os.stdin().readAll()
let hits = text.split("\n").filter({ x.contains(word) })
if hits.isEmpty() {
Os.exit(1)
}
for line in hits {
println(line)
}Properties and relations
Returning an Err from a script also exits with status 1, but it runs the deferred blocks first and writes the error to standard error:
defer { println("cleanup") }
println("start")
return Result.fail("bad input")start
cleanupOs.exit(1) at the same point skips the deferred block:
defer { println("cleanup") }
println("start")
Os.exit(1)startPanic.catch catches panics only, so Os.exit passes through it:
let result = Panic.catch({ Os.exit(4) })
println("never printed: ${result}")Possible issues
Deferred blocks do not run, so a temporary directory removed by defer stays behind. Remove it before the call:
let dir = try File.tempDir("job-*")
defer { File.removeAll(dir) }
if Os.args().isEmpty() {
_ = File.removeAll(dir)
Os.exit(1)
}The same holds in every goroutine: a worker's deferred block does not run when another goroutine exits:
let started: Channel[bool] = Channel.new()
let stop: Channel[bool] = Channel.new()
go {
defer { println("worker cleanup") }
Channel.send(started, true)
Channel.receive(stop)
}
Channel.receive(started)
println("exiting")
Os.exit(5)exitingWhat a buffered handle holds is lost, because Os.exit does not flush it:
let out = File.buffered(Os.stdout())
try out.writeLine("lost")
Os.exit(0)Flush it first:
let out = File.buffered(Os.stdout())
try out.writeLine("kept")
try out.flush()
Os.exit(0)keptIn a test, Os.exit ends ant test with its status, and the tests after it do not run:
test "adds" {
assert(1 + 1 == 2)
}
test "stops the run" {
Os.exit(3)
}
test "never runs" {
assert(false)
}See also
Os.args · Os.interrupt · Panic.catch · File.buffered · panic · defer
