Skip to content

os/exec: exec.CommandContext(...).Output() does not respect context timeout #57129

Closed as not planned
@lfyuomr-gylo

Description

@lfyuomr-gylo

What version of Go are you using (go version)?

$ go version
go version go1.19 darwin/arm64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

I create the following two files

go env Output
$ go env
GO111MODULE="on"
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/levkhotov/Library/Caches/go-build"
GOENV="/Users/levkhotov/Library/Application Support/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE=""
GOMODCACHE="/Users/levkhotov/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/levkhotov/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
GOVCS=""
GOVERSION="go1.19.4"
GCCGO="gccgo"
GOAMD64="v1"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD="/Users/levkhotov/anki-rest-helper/go.mod"
GOWORK=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -arch x86_64 -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/3k/z3gl3j7n0p5cr2z0kh6xftcw0000gn/T/go-build1154024858=/tmp/go-build -gno-record-gcc-switches -fno-common"

What did you do?

Create two files:

main.go
package main

import (
	"context"
	"fmt"
	"os/exec"
	"time"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()

	if _, err := exec.CommandContext(ctx, "./hang.sh").Output(); err != nil {
		fmt.Println("cmd: ", err.Error())
		fmt.Println("ctx: ", ctx.Err().Error())
	}
}
hang.sh
#!/usr/bin/env bash

sleep 100
echo 'foo'

Then run

chmod +x hang.sh
go run ./main.go

What did you expect to see?

I expect the program to complete in approximately 1 second with the following output:

cmd:  signal: killed
ctx:  context deadline exceeded

What did you see instead?

Program completes with the expected output, but only after 100 seconds.

Interestingly enough, when I replace .Output() with Run(), the program completes in 1 second as expected.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions