Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

os/exec のサンプル #87

Closed
devlights opened this issue Jul 3, 2019 · 1 comment · Fixed by #355
Closed

os/exec のサンプル #87

devlights opened this issue Jul 3, 2019 · 1 comment · Fixed by #355

Comments

@devlights
Copy link
Owner

devlights commented Jul 3, 2019

コマンド実行

一発で結果取得

exec.Command("ls").Output()

入出力をきっちり扱う場合

cmd := exec.Command("tr", "a-z", "A-Z")
stdin, _ := cmd.StdinPipe()
stdout, _ := cmd.StdoutPipe()
stderr, _ := cmd.StderrPipe()

err = cmd.Start()


var wg sync.WaitGroup
wg.Add(3)

go func() {
	_, err := io.Copy(stdin, src)
	if e, ok := err.(*os.PathError); ok && e.Err == syscall.EPIPE {
		// ignore EPIPE
	} else if err != nil {
		log.Println("stdin err", err)
	}

	stdin.Close()
	wg.Done()
}()

go func() {
	io.Copy(dst, stdout)
	stdout.Close()
	wg.Done()
}()

go func() {
	io.Copy(errDst, stderr)
	stderr.Close()
	wg.Close()
}()

wg.Wait()

return cmd.Wait()

書き込みと読み込みは平行で行う必要がある。コマンド間の入出力をつなぐ pipe にはバッファが存在しているが、外部コマンドが入力を読み取っていないのにGoからバッファを超えて書き込もうとするとブロックするため。同様に外部コマンドの出力をGoで読み取らないでいると、外部コマンドが出力でブロックしてしまい、動作がとまってしまう可能性がある。

外部コマンドを shell 経由で起動する(Unix系)

out, err := exec.Command("sh", "-c", "ls -l").Output()
exec.Command("sh", "-c", "ls | grep xxx").Output()
@devlights
Copy link
Owner Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
No open projects
Dev
Done
Development

Successfully merging a pull request may close this issue.

1 participant