26
19

More than 5 years have passed since last update.

Goでコマンドを実行して終了コードを取得する方法

Last updated at Posted at 2013-09-01

2019-03-17追記 Go 1.12からはpkg/os/ProcessState.ExitCode()で取得可能です

pkg/os/ProcessState.ExitCode()を使って以下のように書けます。

    cmd := exec.Command("uname", "-a")
    cmd.Run()
    exitCode := cmd.ProcessState.ExitCode()

元記事

実行するコマンドはCommand()で作ってRun()するかStart()してWait()します。終了コードが0以外の場合はExitErrorが帰ります。このos.ProcessStateからSys()を取り出してsyscall.WaitStatus()にキャストして
ExitStatus()でコードが取れます。

https://groups.google.com/d/msg/golang-nuts/8XIlxWgpdJw/Z8s2N-SoWHsJ を参考にしました。ただ、APIが変わったのか、syscall.WaitStatusからコードを取り出すのはExitCodeではなくExitStatus()でした。

    cmd := exec.Command("uname", "-a")
    err := cmd.Run()
    var exitStatus int
    if err != nil {
        if e2, ok := err.(*exec.ExitError); ok {
            if s, ok := e2.Sys().(syscall.WaitStatus); ok {
                exitStatus = s.ExitStatus()
            } else {
                panic(errors.New("Unimplemented for system where exec.ExitError.Sys() is not syscall.WaitStatus."))
            }
        }
    } else {
        exitStatus = 0
    }

os.ProcessStateのSys()に"Convert it to the appropriate underlying type, such as syscall.WaitStatus on Unix, to access its contents."と書いてありますので、OSによっては違う型になっている可能性もあります。

ソースを確認したところ、Windowsでもsyscall.WaitStatusでした。

http://golang.org/src/pkg/os/exec_windows.go#L42
go:src/pkg/os/exec_windows.go:42
return &ProcessState{p.Pid, syscall.WaitStatus{ExitCode: ec}, &u}, nil

26
19
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
19