Last active
April 17, 2018 18:02
-
-
Save myitcv/3781f8f89e1d0484118fc290595c474d to your computer and use it in GitHub Desktop.
stderr stdout demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
go build -o main -tags main && go build -o main2 -tags main2 | |
# run main2 by itself | |
./main2 | |
# exits with a non-zero exit code and gives: | |
# | |
# 1st line to stdout | |
# 2nd line to stderr | |
# 3rd line to stdout | |
# run main which calls main2 | |
./main | |
# exits with a non-zero exit code and gives" | |
# | |
# we got an error running main2: exit status 1 | |
# Stdout was: | |
# 1st line to stdout | |
# 3rd line to stdout | |
# Stderr was: | |
# 2nd line to stderr | |
# i.e. we lose the interleaving of stderr and stdout - this is, more often than not, useful/ | |
# critical context when we have a non-zero exit status |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// +build main | |
package main | |
import ( | |
"bytes" | |
"fmt" | |
"os" | |
"os/exec" | |
) | |
func main() { | |
stdout := new(bytes.Buffer) | |
stderr := new(bytes.Buffer) | |
cmd := exec.Command("./main2") | |
cmd.Stdout = stdout | |
cmd.Stderr = stderr | |
if err := cmd.Run(); err != nil { | |
fmt.Fprintf(os.Stderr, "we got an error running main2: %v\n", err) | |
fmt.Fprintf(os.Stderr, "Stdout was:\n%s", stdout.Bytes()) | |
fmt.Fprintf(os.Stderr, "Stderr was:\n%s", stderr.Bytes()) | |
os.Exit(1) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// +build main2 | |
package main | |
import ( | |
"fmt" | |
"os" | |
) | |
func main() { | |
fmt.Fprintln(os.Stdout, "1st line to stdout") | |
fmt.Fprintln(os.Stderr, "2nd line to stderr") | |
fmt.Fprintln(os.Stdout, "3rd line to stdout") | |
os.Exit(1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment