File: stdin.go

package info (click to toggle)
packer 1.3.4%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 8,324 kB
  • sloc: python: 619; sh: 557; makefile: 111
file content (38 lines) | stat: -rw-r--r-- 915 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main

import (
	"io"
	"log"
	"os"
	"os/signal"
	"syscall"
)

// setupStdin switches out stdin for a pipe. We do this so that we can
// close the writer end of the pipe when we receive an interrupt so plugins
// blocked on reading from stdin are unblocked.
func setupStdin() {
	// Create the pipe and swap stdin for the reader end
	r, w, _ := os.Pipe()
	originalStdin := os.Stdin
	os.Stdin = r

	// Create a goroutine that copies data from the original stdin
	// into the writer end of the pipe forever.
	go func() {
		defer w.Close()
		io.Copy(w, originalStdin)
	}()

	// Register a signal handler for interrupt in order to close the
	// writer end of our pipe so that readers get EOF downstream.
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt, syscall.SIGTERM)

	go func() {
		defer signal.Stop(ch)
		defer w.Close()
		<-ch
		log.Println("Closing stdin because interrupt received.")
	}()
}