Created
April 23, 2015 00:45
-
-
Save dqminh/36d8233389bd1eb51483 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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