Skip to content

Instantly share code, notes, and snippets.

@ujiro99
Last active May 1, 2018 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ujiro99/276d1247497f30aba9d866ed23bac645 to your computer and use it in GitHub Desktop.
Save ujiro99/276d1247497f30aba9d866ed23bac645 to your computer and use it in GitHub Desktop.
Write more than 4K bytes to StdinPipe.
package main
import (
"bytes"
"fmt"
"log"
"os/exec"
"io"
)
func main() {
cmd := exec.Command("less")
pype, err := cmd.StdinPipe()
if err != nil {
log.Fatal(err)
}
bytes4k := generateBytes(1024 * 4)
fmt.Println("bytes generated.")
go writeBytes(pype, bytes4k)
// writeBytes(pype, bytes4k) // Can't write. Write is locked.
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Println("finished.")
}
func generateBytes(num int) []byte {
byte := bytes.NewBuffer(make([]byte, 0, num))
for i := 0; i < num; i++ {
byte.WriteByte('0')
}
return byte.Bytes()
}
func writeBytes(in io.WriteCloser, bytes []byte) {
defer in.Close()
_, err := in.Write(bytes)
if err != nil {
log.Fatal(err)
}
fmt.Println("written bytes to pipe.")
_, err = in.Write([]byte{'0'})
if err != nil {
log.Fatal(err)
}
fmt.Println("written 1 byte to pipe.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment