Skip to content

Instantly share code, notes, and snippets.

@blackandred
Last active April 6, 2022 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blackandred/c77a6b83d4d5c6e662ba19b1618b75b7 to your computer and use it in GitHub Desktop.
Save blackandred/c77a6b83d4d5c6e662ba19b1618b75b7 to your computer and use it in GitHub Desktop.
Cancel Context, when exec.Command{} process fails
type ReadCloserWithCancellationWhenProcessFails struct {
Parent io.ReadCloser
Process *exec.Cmd
Cancel func()
}
func (r ReadCloserWithCancellationWhenProcessFails) Read(p []byte) (n int, err error) {
return r.Parent.Read(p)
}
func (r ReadCloserWithCancellationWhenProcessFails) Close() error {
err := r.Process.Wait()
exitCode := 0
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 {
exitCode = 1
}
} else {
ws := r.Process.ProcessState.Sys().(syscall.WaitStatus)
exitCode = ws.ExitStatus()
}
if exitCode > 0 {
log.Errorf("Canceling upload due to process failure - exitCode: %v", exitCode)
r.Cancel()
}
return r.Parent.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment