Skip to content

Instantly share code, notes, and snippets.

@deitch
Created February 16, 2018 14:17
Show Gist options
  • Save deitch/ad6cb7b0801abe920be3aed1839cb722 to your computer and use it in GitHub Desktop.
Save deitch/ad6cb7b0801abe920be3aed1839cb722 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"io"
"log"
"os"
"os/exec"
)
func main() {
switch os.Args[1] {
case "buffer":
// FAILS
doBuffers()
case "stdio":
// WORKS
doStdio()
case "pipe":
// WORKS
doPipe()
case "startpipe":
// FAILS
doStartPipe()
case "file":
// WORKS
doFile()
}
}
func doBuffers() {
cmd := exec.Command("/usr/bin/runc", "create", "echo")
cmdStdout := &bytes.Buffer{}
cmdStderr := &bytes.Buffer{}
cmd.Stdout = cmdStdout
cmd.Stderr = cmdStderr
cmd.Run()
os.Stdout.Write(cmdStdout.Bytes())
os.Stderr.Write(cmdStderr.Bytes())
log.Printf("Done buffers")
}
func doStdio() {
cmd := exec.Command("/usr/bin/runc", "create", "echo")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
log.Printf("Done stdio")
}
func doPipe() {
cmd := exec.Command("/usr/bin/runc", "create", "echo")
outPipe, err := cmd.StdoutPipe()
if err != nil {
log.Fatalf("Could not get stdout pipe")
}
errPipe, err := cmd.StderrPipe()
if err != nil {
log.Fatalf("Could not get stderr pipe")
}
cmd.Run()
io.Copy(os.Stdout, outPipe)
io.Copy(os.Stderr, errPipe)
log.Printf("Done pipes")
}
func doStartPipe() {
cmd := exec.Command("/usr/bin/runc", "create", "echo")
outPipe, err := cmd.StdoutPipe()
if err != nil {
log.Fatalf("Could not get stdout pipe")
}
errPipe, err := cmd.StderrPipe()
if err != nil {
log.Fatalf("Could not get stderr pipe")
}
cmd.Start()
io.Copy(os.Stdout, outPipe)
io.Copy(os.Stderr, errPipe)
cmd.Wait()
log.Printf("Done startpipes")
}
func doFile() {
fStdout, err := os.OpenFile("/tmp/stdout.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatalf("Error opening stdout log file: %v", err)
}
defer fStdout.Close()
fStderr, err := os.OpenFile("/tmp/stderr.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatalf("Error opening stderr log file: %v", err)
}
defer fStderr.Close()
cmd := exec.Command("/usr/bin/runc", "create", "echo")
cmd.Stdout = fStdout
cmd.Stderr = fStderr
cmd.Run()
log.Printf("Done files to /tmp/stdout.log and /tmp/stderr.log")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment