github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/cmds/core/elvish/eval/std_ports.go (about)

     1  package eval
     2  
     3  import (
     4  	"os"
     5  	"sync"
     6  
     7  	"github.com/u-root/u-root/cmds/core/elvish/eval/vals"
     8  )
     9  
    10  const (
    11  	stdoutChanSize = 32
    12  	stderrChanSize = 32
    13  )
    14  
    15  type stdPorts struct {
    16  	ports       [3]*Port
    17  	relayerWait *sync.WaitGroup
    18  }
    19  
    20  func newStdPorts(stdin, stdout, stderr *os.File, prefix string) stdPorts {
    21  	stdoutChan := make(chan interface{}, stdoutChanSize)
    22  	stderrChan := make(chan interface{}, stderrChanSize)
    23  
    24  	relayerWait := new(sync.WaitGroup)
    25  	relayerWait.Add(2)
    26  	go relayChanToFile(stdoutChan, stdout, prefix, relayerWait)
    27  	go relayChanToFile(stderrChan, stderr, prefix, relayerWait)
    28  
    29  	return stdPorts{
    30  		[3]*Port{
    31  			{File: stdin, Chan: ClosedChan},
    32  			{File: stdout, Chan: stdoutChan, CloseChan: true},
    33  			{File: stderr, Chan: stderrChan, CloseChan: true},
    34  		},
    35  		relayerWait,
    36  	}
    37  }
    38  
    39  func relayChanToFile(ch <-chan interface{}, file *os.File, prefix string, w *sync.WaitGroup) {
    40  	for v := range ch {
    41  		file.WriteString(prefix)
    42  		file.WriteString(vals.Repr(v, initIndent))
    43  		file.WriteString("\n")
    44  	}
    45  	w.Done()
    46  }
    47  
    48  func (ep *stdPorts) close() {
    49  	ep.ports[1].Close()
    50  	ep.ports[2].Close()
    51  	ep.relayerWait.Wait()
    52  }