Skip to content

os/exec: close read end of stdout/stderr pipe when copy loop stops #10400

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
pstibrany opened this issue Apr 9, 2015 · 1 comment
Closed
Milestone

Comments

@pstibrany
Copy link

Writer set to exec.Cmd.Stdout (or Stderr) may fail. When that happens, underlying pipe is not closed, and command continues to run without noticing that something is wrong.

Here is an example. This little program starts "ls -lR /", which (usually) runs for a long time and produces lot of output. When our brokenWriter returns error, ls command continues to run. Buffer associated with the pipe in the kernel eventually gets filled, which in turn blocks ls, which will then never finish.

I think the solution is to close underlying pr pipe when goroutine created by Cmd.writerDescriptor detects error, similar to what goroutine in stdin method does

package main

import "os"
import "os/exec"
import "io"
import "log"
import "fmt"

type brokenWriter struct {
    w io.Writer
    c int
}

func (bw *brokenWriter) Write(data []byte) (int, error) {
    if bw.c > 0 {
        bw.c = bw.c - 1
        return bw.w.Write(data)
    }
    log.Println("returning error from broken writer")
    return 0, fmt.Errorf("broken writer")
}

func main() {
    cmd := exec.Command("ls", "-lR", "/")

    cmd.Stdout = &brokenWriter{os.Stdout, 1}

    err := cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
}
@ianlancetaylor ianlancetaylor changed the title When exec.Cmd.Stdout writer returns error, associated pipe is not closed, and command continues to run, potentionally creating a deadlock os/exec: When Cmd.Stdout writer returns error, associated pipe is not closed, and command continues to run, potentionally creating a deadlock Apr 9, 2015
@ianlancetaylor ianlancetaylor added this to the Go1.5 milestone Apr 9, 2015
@rsc rsc changed the title os/exec: When Cmd.Stdout writer returns error, associated pipe is not closed, and command continues to run, potentionally creating a deadlock os/exec: close read end of stdout/stderr pipe when copy loop stops Jul 15, 2015
@gopherbot
Copy link
Contributor

CL https://golang.org/cl/12537 mentions this issue.

@rsc rsc closed this as completed in 92390e4 Jul 22, 2015
@golang golang locked and limited conversation to collaborators Aug 5, 2016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants