Skip to content

Instantly share code, notes, and snippets.

@dqminh
Created April 23, 2015 00:45
Show Gist options
  • Save dqminh/36d8233389bd1eb51483 to your computer and use it in GitHub Desktop.
Save dqminh/36d8233389bd1eb51483 to your computer and use it in GitHub Desktop.
package main
import (
"log"
"os"
"os/exec"
"time"
)
func main() {
if len(os.Args) != 2 {
log.Fatalf("required: go run test-exec.go docker-exec|nsinit-exec|echo|docker-run")
}
switch os.Args[1] {
case "docker-exec":
main1()
case "nsinit-exec":
main2()
case "echo":
main3()
case "docker-run":
main4()
}
}
func main1() {
exec.Command("docker", "stop", "testing").Run()
exec.Command("docker", "rm", "testing").Run()
defer func() {
exec.Command("docker", "stop", "testing").Run()
exec.Command("docker", "rm", "testing").Run()
}()
exec.Command("docker", "run", "-d", "--name", "testing", "busybox", "top").Run()
time.Sleep(1 * time.Second)
cmd := exec.Command("docker", "exec", "-i", "testing", "echo", "hello")
stdin, err := cmd.StdinPipe()
if err != nil {
panic(err)
}
defer stdin.Close()
if err := cmd.Start(); err != nil {
panic(err)
}
time.Sleep(1 * time.Second)
n, err := stdin.Write([]byte("hello"))
log.Println(n, err)
}
func main2() {
cmd := exec.Command("sudo", "nsinit", "exec", "top")
cmd.Dir = "/busybox"
if err := cmd.Start(); err != nil {
panic(err)
}
time.Sleep(1 * time.Second)
defer cmd.Process.Kill()
exec := exec.Command("sudo", "nsinit", "exec", "true")
cmd.Dir = "/busybox"
stdin, err := exec.StdinPipe()
if err != nil {
panic(err)
}
defer stdin.Close()
if err := exec.Start(); err != nil {
panic(err)
}
time.Sleep(1 * time.Second)
n, err := stdin.Write([]byte("hello"))
log.Println(n, err)
}
func main3() {
cmd := exec.Command("echo", "hello")
stdin, err := cmd.StdinPipe()
if err != nil {
panic(err)
}
defer stdin.Close()
if err := cmd.Start(); err != nil {
panic(err)
}
time.Sleep(1 * time.Second)
n, err := stdin.Write([]byte("hello"))
log.Println(n, err)
}
func main4() {
cmd := exec.Command("docker", "run", "-i", "--rm", "busybox", "echo", "hello")
stdin, err := cmd.StdinPipe()
if err != nil {
panic(err)
}
defer stdin.Close()
if err := cmd.Start(); err != nil {
panic(err)
}
time.Sleep(1 * time.Second)
n, err := stdin.Write([]byte("hello"))
log.Println(n, err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment