Skip to content

os/exec: shell command can't be killed when output redirected with cmd.exe #22381

@math2001

Description

@math2001

When I run a shell command with cmd.exe and redirect either the stdout or the stderr, the command cannot be killed (it says that it has been killed once the command is done, but it keeps running).

Here's the code (try to comment out cmd.Stdout =... and cmd.Stderr =...):

package main

import "os/exec"
import "fmt"
import "time"
import "bytes"

func main() {
    cmd := exec.Command("cmd.exe", "/C", "sleep 2")
    var stdout bytes.Buffer
    var stderr bytes.Buffer

    cmd.Stdout = &stdout
    cmd.Stderr = &stderr

    start := time.Now()
    fmt.Println(cmd.Start())
    timer := time.AfterFunc(1 * time.Second, func () {
        fmt.Println("killed", cmd.Process.Kill())

    })
    fmt.Println(cmd.Wait())
    timer.Stop()
    fmt.Println(time.Since(start))
}

It outputs this:

<nil>
killed <nil>
exit status 1
2.0313611s

And without the redirects, the output is:

<nil>
killed <nil>
exit status 1
1.0205677s

System details

Details
go version go1.9.1 windows/amd64
GOARCH="amd64"
GOBIN=""
GOEXE=".exe"
GOHOSTARCH="amd64"
GOHOSTOS="windows"
GOOS="windows"
GOPATH="C:\Users\Home\gopackages"
GORACE=""
GOROOT="C:\Go"
GOTOOLDIR="C:\Go\pkg\tool\windows_amd64"
GCCGO="gccgo"
CC="gcc"
GOGCCFLAGS="-m64 -mthreads -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOROOT/bin/go version: go version go1.9.1 windows/amd64
GOROOT/bin/go tool compile -V: compile version go1.9.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions