io.ReadCloser returned by cmd.StdoutPipe() leads to panic if cmd.Stdout has been altered

-4

I want to parse the standard output of an external command. To do this I use exec.StdoutPipe like this:

func main() {
    // ...
    cmd := exec.Command(commandString)
    stdoutIn, _ := cmd.StdoutPipe()
    cmd.Start()
    go monitorCommand(stdoutIn, watchphrase)
    // ...
}

func monitorCommand(output io.ReadCloser, watchphrase string) {
    scanner := bufio.NewScanner(output)
    go func() {
        for scanner.Scan() {
            sText := scanner.Text()
            if strings.Contains(sText, watchphrase) {
                break
            }
        }
    }()
    // ...
}

Now I additionally want to set the commands Stdout to an io.Writer. To do so I modify the above code like this:

    // ...
    cmd := exec.Command(commandString)
    cmd.Stdout = debugText
    stdoutIn, _ := cmd.StdoutPipe()
    // ...

But this change causes it panic scanner.Scan():


panic: runtime error: invalid memory address or nil pointer dereference [signal 0xc0000005 code=0x0 addr=0x18 pc=0x5e4f1c] goroutine 178 [running]:
bufio.(*Scanner).Scan(0xc0009e2000, 0xc0001e3fc0) C:/Go/src/bufio/scan.go:213 +0x7c
main.monitorCommand.func1(0xc0009e2000, 0xc000057240, 0x5, 0xc0002bc000) C:/Users/jakob/Documents/projects/F1/F1viewer/main.go:229
created by main.monitorCommand C:/Users/jakob/Documents/projects/F1/F1viewer/main.go:228 +0x104

There is no indication that changing the cmd.Stdout should affect cmd.StdoutPipe() the in the godoc

go
io
asked on Stack Overflow Jun 17, 2019 by smfs

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0