golang/go

cmd/go: run does not relay signals to child process

Open

#40,467 opened on Jul 29, 2020

View on GitHub
 (5 comments) (7 reactions) (0 assignees)Go (19,008 forks)batch import
GoCommandNeedsInvestigationhelp wanted

Repository metrics

Stars
 (133,883 stars)
PR merge metrics
 (No merged PRs in 30d)

Description

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

Does this issue reproduce with the latest release?

Yes

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

What did you do?

# This will correctly exit
exec go run parent.go build

# This will block
exec go run parent.go


-- parent.go --
package main

import (
	"bufio"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
)

func main() {
	var cmdArgs []string

	if len(os.Args) == 2 && os.Args[1] == "build" {
		td, err := ioutil.TempDir("", "")
		if err != nil {
			log.Fatalf("failed to create temp dir: %v", err)
		}
		defer os.RemoveAll(td)
		out := filepath.Join(td, "child")
		build := exec.Command("go", "build", "-o", out, "child.go")
		if out, err := build.CombinedOutput(); err != nil {
			log.Fatalf("failed to run [%v]: %v\n%s", build, err, out)
		}
		cmdArgs = []string{out}
	} else {
		cmdArgs = []string{"go", "run", "child.go"}
	}

	r, w := io.Pipe()

	done := make(chan struct{})
	child := exec.Command(cmdArgs[0], cmdArgs[1:]...)
	child.Stdout = w

	if err := child.Start(); err != nil {
		log.Fatalf("failed to start child [%v]: %v", child, err)
	}

	go func() {
		if err := child.Wait(); err != nil {
			log.Fatalf("child process [%v] failed: %v", child, err)
		}
		close(done)
	}()

	// Continue once we have read the first line
	if _, _, err := bufio.NewReader(r).ReadLine(); err != nil {
		log.Fatalf("failed to read start line from child: %v", err)
	}

	if err := child.Process.Signal(os.Interrupt); err != nil {
		log.Fatalf("failed to notify child process")
	}

	<-done
}
-- child.go --
package main

import (
	"fmt"
	"os"
	"os/signal"
)

func main() {
	sigint := make(chan os.Signal, 1)
	signal.Notify(sigint, os.Interrupt)
	fmt.Println("Started")
	<-sigint
}

What did you expect to see?

The interrupt signal to be passed to the child process by go run, I think?

What did you see instead?

The go run child process does not relay the interrupt signal to the child process.

cc @bcmills @jayconrod @matloob

Contributor guide