Skip to content

Instantly share code, notes, and snippets.

@yifan-gu
Last active August 29, 2015 13:56
Show Gist options
  • Save yifan-gu/8866492 to your computer and use it in GitHub Desktop.
Save yifan-gu/8866492 to your computer and use it in GitHub Desktop.
if reaching EOF, splice won't block
$ go build testsplice.go
$ echo "hello splice" | ./testsplice
$ splicing... buffer size: 4096
recv: hello splice
count: 13
finish
package main
import (
"fmt"
"os"
"syscall"
"time"
)
func main() {
var err error
finish := make(chan bool, 1)
pipe := make([]*os.File, 2)
pipe[0], pipe[1], err = os.Pipe()
if err != nil {
panic(err.Error())
}
go func() {
fmt.Println("splicing... buffer size:", 4096)
n, err := syscall.Splice(int(os.Stdin.Fd()), nil, int(pipe[1].Fd()), nil, 4096, 0)
if err != nil {
panic(err.Error())
}
b := make([]byte, 4096)
_, err = pipe[0].Read(b)
if err != nil {
panic(err.Error())
}
fmt.Printf("recv: %scount: %d\n", string(b), n)
finish <- true
}()
select {
case <-finish:
fmt.Println("finish")
case <-time.After(10 * time.Second):
fmt.Println("time out")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment