/
pipe.go
44 lines (37 loc) · 1.12 KB
/
pipe.go
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
39
40
41
42
43
44
// +build !windows
package aio
import (
"os"
"syscall"
)
// PipeFlag might be used to specify options when creating
// a pipe.
type PipeFlag int
const (
// ReadNonBlock causes the read end of the pipe to be non-blocking.
ReadNonBlock PipeFlag = 1 << iota
// ReadNonBlock causes the write end of the pipe to be non-blocking.
WriteNonBlock
)
// Pipe returns a connected pair of Files; reads from
// r return bytes written to w. It returns the files and an error, if any.
// Optionally, r or w might be set to non-blocking mode using the appropriate
// flags. To obtain a blocking pipe just pass 0 as the flag.
func Pipe(flag PipeFlag) (r *os.File, w *os.File, err error) {
var p [2]int
syscall.ForkLock.RLock()
if err := syscall.Pipe(p[:]); err != nil {
syscall.ForkLock.RUnlock()
return nil, nil, os.NewSyscallError("pipe", err)
}
syscall.CloseOnExec(p[0])
syscall.CloseOnExec(p[1])
if flag&ReadNonBlock != 0 {
syscall.SetNonblock(p[0], true)
}
if flag&WriteNonBlock != 0 {
syscall.SetNonblock(p[1], true)
}
syscall.ForkLock.RUnlock()
return os.NewFile(uintptr(p[0]), "|0"), os.NewFile(uintptr(p[1]), "|1"), nil
}