elvish/eval/port.go

60 lines
1.2 KiB
Go
Raw Normal View History

package eval
import (
"os"
)
2016-02-09 03:11:20 +08:00
// Port conveys data stream. It always consists of a byte band and a channel band.
type Port struct {
File *os.File
Chan chan interface{}
2016-02-09 03:11:20 +08:00
CloseFile bool
CloseChan bool
}
2016-02-09 08:40:36 +08:00
// Fork returns a copy of a Port with the Close* flags unset.
func (p *Port) Fork() *Port {
return &Port{p.File, p.Chan, false, false}
}
// Close closes a Port.
2016-02-09 03:27:05 +08:00
func (p *Port) Close() {
2016-01-23 01:05:15 +08:00
if p == nil {
return
}
2016-02-09 03:11:20 +08:00
if p.CloseFile {
p.File.Close()
2016-01-23 01:05:15 +08:00
}
2016-02-09 03:11:20 +08:00
if p.CloseChan {
close(p.Chan)
2016-01-23 01:05:15 +08:00
}
}
2016-10-10 22:54:58 +08:00
var (
// ClosedChan is a closed channel, suitable for use as placeholder channel input.
ClosedChan = make(chan interface{})
// BlackholeChan is channel writes onto which disappear, suitable for use as
// placeholder channel output.
BlackholeChan = make(chan interface{})
// DevNull is /dev/null.
DevNull *os.File
2019-04-19 05:15:34 +08:00
// DevNullClosedChan is a port made up from DevNull and ClosedChan,
// suitable as placeholder input port.
DevNullClosedChan *Port
2016-10-10 22:54:58 +08:00
)
func init() {
close(ClosedChan)
go func() {
for range BlackholeChan {
}
}()
2016-10-10 22:54:58 +08:00
var err error
DevNull, err = os.Open(os.DevNull)
2016-10-10 22:54:58 +08:00
if err != nil {
os.Stderr.WriteString("cannot open " + os.DevNull + ", shell might not function normally\n")
2016-10-10 22:54:58 +08:00
}
DevNullClosedChan = &Port{File: DevNull, Chan: ClosedChan}
2016-10-10 22:54:58 +08:00
}