Skip to content

os/exec: CommandContext does not forward the context's error on timeout #21880

@aruiz14

Description

@aruiz14

Go version: Latest release - 1.9

Using CommandContext in combination with Context.WithTimeout shows very few information about the reason of the error when the execution times out.
Using a small variation of the CommandContext example
proves this:

package main

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

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

        if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
                fmt.Println("cmd: ", err)
                fmt.Println("ctx: ", ctx.Err())
        }
}

Output:

cmd:  signal: killed
ctx:  context deadline exceeded

Also, if the context is already done then the cmd.Run gets called, the error matches the context's error:

package main

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

func main() {
        ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
        defer cancel()
        time.Sleep(150 * time.Millisecond)

        if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
                fmt.Println("cmd: ", err.Error())
                fmt.Println("ctx: ", ctx.Err().Error())
        }
}

Output:

cmd:  context deadline exceeded
ctx:  context deadline exceeded

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions