Home >Backend Development >Golang >How to Retrieve the Exit Code from `os/exec` in Go?

How to Retrieve the Exit Code from `os/exec` in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-23 10:37:58454browse

How to Retrieve the Exit Code from `os/exec` in Go?

How to Get Exit Code in Go

When using the os/exec package to execute a command, one may encounter the common concern of obtaining the exit code. While the documentation provides the Process.Success() method to indicate whether the process exited without errors, it does not provide an explicit way to retrieve the actual exit code.

One workaround to acquire the exit code for Linux-based systems is to leverage the syscall package. Here's an improved code snippet:

package main

import (
    "log"
    "os/exec"
    "syscall"
)

func main() {
    cmd := exec.Command("somecommand", "parameter")
    if err := cmd.Run(); err != nil {
        if exiterr, ok := err.(*exec.ExitError); ok {
            // exiterr.Sys() is a syscall.WaitStatus.
            log.Printf("Exit Status: %d", exiterr.Sys().(syscall.WaitStatus).ExitStatus())
        } else {
            log.Fatalf("cmd.Run: %v", err)
        }
    }
}

This approach uses the WaitStatus type from the syscall package, which contains an ExitStatus() method to retrieve the exit code for processes running on Linux and other UNIX-like operating systems.

For Windows systems, this method will not work as it does not provide the same concept of exit codes. Instead, you can opt for alternative approaches such as using cmd.exe's /c option to execute a command and parse the output for error codes.

By adapting these techniques based on your operating system, you can effectively retrieve the exit code of external commands executed through the os/exec package in Go.

The above is the detailed content of How to Retrieve the Exit Code from `os/exec` in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn