Skip to content

Instantly share code, notes, and snippets.

@kayrus
Created April 18, 2016 15:43
Show Gist options
  • Save kayrus/ad9de9565215a5d7302ee446a4c12a1c to your computer and use it in GitHub Desktop.
Save kayrus/ad9de9565215a5d7302ee446a4c12a1c to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io"
"os"
"syscall"
)
func main() {
for i := 0; i<3; i++ {
oldStdin, _ := syscall.Dup(syscall.Stdin)
go func(dst io.Writer, src io.Reader) error {
var err error
buf := make([]byte, 32*1024)
for {
fmt.Print("prepare to read\n")
nr, er := src.Read(buf)
fmt.Printf("read done: %d bytes\n", nr)
if nr > 0 {
fmt.Print("prepare to write\n")
nw, ew := dst.Write(buf[0:nr])
fmt.Printf("write done: %d bytes\n", nw)
if ew != nil {
fmt.Print("interrupt ew != nil\n")
err = ew
break
}
if nr != nw {
fmt.Print("interrupt nr != nw\n")
err = io.ErrShortWrite
break
}
}
if er == io.EOF {
fmt.Print("interrupt EOF\n")
break
}
if er != nil {
fmt.Print("interrupt er != nil\n")
err = er
break
}
}
fmt.Print("Copy finished\n")
return err
}(os.Stdout, os.Stdin)
fmt.Print("Closing stdin\n")
os.Stdin.Close()
fmt.Print("Closed stdin\n")
syscall.Dup2(oldStdin, syscall.Stdin)
syscall.Close(oldStdin)
os.Stdin = os.NewFile(uintptr(syscall.Stdin), "/dev/stdin")
var ans string
fmt.Fprint(os.Stderr, "Scanning:\n")
_, err := fmt.Scanf("%s\n", &ans)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to scan: %#v\n",err.Error())
} else {
fmt.Fprintf(os.Stderr, "ans: \"%s\"\n",ans)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment