Improve spawning-process example with error-checking
This commit is contained in:
@@ -17,10 +17,10 @@ func main() {
|
||||
// to represent this external process.
|
||||
dateCmd := exec.Command("date")
|
||||
|
||||
// `.Output` is another helper that handles the common
|
||||
// case of running a command, waiting for it to finish,
|
||||
// and collecting its output. If there were no errors,
|
||||
// `dateOut` will hold bytes with the date info.
|
||||
// The `Output` method runs the command, waits for it
|
||||
// to finish and collects its standard output.
|
||||
// If there were no errors, `dateOut` will hold bytes
|
||||
// with the date info.
|
||||
dateOut, err := dateCmd.Output()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@@ -28,6 +28,23 @@ func main() {
|
||||
fmt.Println("> date")
|
||||
fmt.Println(string(dateOut))
|
||||
|
||||
// `Output` and other methods of `Command` will return
|
||||
// `*exec.Error` if there was a problem executing the
|
||||
// command (e.g. wrong path), and `*exec.ExitError`
|
||||
// if the command ran but exited with a non-zero return
|
||||
// code.
|
||||
_, err = exec.Command("date", "-x").Output()
|
||||
if err != nil {
|
||||
switch e := err.(type) {
|
||||
case *exec.Error:
|
||||
fmt.Println("failed executing:", err)
|
||||
case *exec.ExitError:
|
||||
fmt.Println("command exit rc =", e.ExitCode())
|
||||
default:
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Next we'll look at a slightly more involved case
|
||||
// where we pipe data to the external process on its
|
||||
// `stdin` and collect the results from its `stdout`.
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
aaedc48f74409cef2b8e9ad624aa1c4639ce630d
|
||||
s-T7gxeD7hH
|
||||
5303cfb969de556a875db17972b4107b6f70ba10
|
||||
rmnQdR-dMWU
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
# as if we had run them directly from the command-line.
|
||||
$ go run spawning-processes.go
|
||||
> date
|
||||
Wed Oct 10 09:53:11 PDT 2012
|
||||
Thu 05 May 2022 10:10:12 PM PDT
|
||||
|
||||
# date doesn't have a `-x` flag so it will exit with
|
||||
# an error message and non-zero return code.
|
||||
command exited with rc = 1
|
||||
> grep hello
|
||||
hello grep
|
||||
|
||||
|
||||
Reference in New Issue
Block a user