Determining Exit Codes in Go's os/exec Package
In Go, the os/exec package provides a convenient mechanism for executing system commands. However, obtaining the exit code of an executed command can be a bit tricky.
The Problem
The Command.Run() and Command.Output() methods do not provide direct access to the exit code. While Command.Wait() will return an error for non-zero exit codes, this error does not include the specific exit code value.
A Cross-Platform Solution
Unfortunately, there is no platform-agnostic API for retrieving exit codes. However, for Linux systems, the following approach can be used:
import ( "syscall" ) ... // Attempt to execute the command if err := cmd.Start(); err != nil { log.Fatalf("cmd.Start: %v", err) } // Wait for the command to complete if err := cmd.Wait(); err != nil { if exitErr, ok := err.(*exec.ExitError); ok { // Convert exit status to an integer exitStatus := exitErr.ExitCode() log.Printf("Exit Status: %d", exitStatus) } else { log.Fatalf("cmd.Wait: %v", err) } }
In this solution, we rely on a non-standard ExitError structure available in the os/exec package. By checking for its presence, we can access the ExitCode() method to retrieve the exit code.
Limitations
Please note that this approach is specific to Linux and may not work on other platforms. Refer to the os/exec package documentation for alternative methods or consult platform-specific resources.
The above is the detailed content of How Can I Reliably Retrieve Exit Codes from Go's os/exec Package?. For more information, please follow other related articles on the PHP Chinese website!