dtudj42064 2012-04-30 14:42
浏览 63
已采纳

获取退出代码-转到

I'm using the package: os/exec http://golang.org/pkg/os/exec/ to execute a command in the operating system but I don't seem to find the way to get the exit code. I can read the output though

ie.

package main

import(
    "os/exec"
    "bytes"
    "fmt"
    "log"
    )

func main() {
    cmd := exec.Command("somecommand", "parameter")
    var out bytes.Buffer
    cmd.Stdout = &out
    if err := cmd.Run() ; err != nil {
        //log.Fatal( cmd.ProcessState.Success() )
        log.Fatal( err )
    }
    fmt.Printf("%q
", out.String() )
}
  • 写回答

3条回答 默认 最新

  • dongwei1921 2012-04-30 15:02
    关注

    It's easy to determine if the exit code was 0 or something else. In the first case, cmd.Wait() will return nil (unless there is another error while setting up the pipes).

    Unfortunately, there is no platform independent way to get the exit code in the error case. That's also the reason why it isn't part of the API. The following snippet will work with Linux, but I haven't tested it on other platforms:

    package main
    
    import "os/exec"
    import "log"
    import "syscall"
    
    func main() {
        cmd := exec.Command("git", "blub")
    
        if err := cmd.Start(); err != nil {
            log.Fatalf("cmd.Start: %v")
        }
    
        if err := cmd.Wait(); err != nil {
            if exiterr, ok := err.(*exec.ExitError); ok {
                // The program has exited with an exit code != 0
    
                // This works on both Unix and Windows. Although package
                // syscall is generally platform dependent, WaitStatus is
                // defined for both Unix and Windows and in both cases has
                // an ExitStatus() method with the same signature.
                if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
                    log.Printf("Exit Status: %d", status.ExitStatus())
                }
            } else {
                log.Fatalf("cmd.Wait: %v", err)
            }
        }
    }
    

    Just follow the api docs to find out more :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置