Created
July 19, 2017 08:43
-
-
Save boyzhujian/52cdc09a0e91c553a6535c045878f8df to your computer and use it in GitHub Desktop.
go get syscall exit code
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
| package utils | |
| import ( | |
| "bytes" | |
| "log" | |
| "os/exec" | |
| "syscall" | |
| ) | |
| const defaultFailedCode = 1 | |
| func RunCommand(name string, args ...string) (stdout string, stderr string, exitCode int) { | |
| log.Println("run command:", name, args) | |
| var outbuf, errbuf bytes.Buffer | |
| cmd := exec.Command(name, args...) | |
| cmd.Stdout = &outbuf | |
| cmd.Stderr = &errbuf | |
| err := cmd.Run() | |
| stdout = outbuf.String() | |
| stderr = errbuf.String() | |
| if err != nil { | |
| // try to get the exit code | |
| if exitError, ok := err.(*exec.ExitError); ok { | |
| ws := exitError.Sys().(syscall.WaitStatus) | |
| exitCode = ws.ExitStatus() | |
| } else { | |
| // This will happen (in OSX) if `name` is not available in $PATH, | |
| // in this situation, exit code could not be get, and stderr will be | |
| // empty string very likely, so we use the default fail code, and format err | |
| // to string and set to stderr | |
| log.Printf("Could not get exit code for failed program: %v, %v", name, args) | |
| exitCode = defaultFailedCode | |
| if stderr == "" { | |
| stderr = err.Error() | |
| } | |
| } | |
| } else { | |
| // success, exitCode should be 0 if go is ok | |
| ws := cmd.ProcessState.Sys().(syscall.WaitStatus) | |
| exitCode = ws.ExitStatus() | |
| } | |
| log.Printf("command result, stdout: %v, stderr: %v, exitCode: %v", stdout, stderr, exitCode) | |
| return | |
| } | |
| #https://stackoverflow.com/questions/10385551/get-exit-code-go |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment