英文:
Strange behaviour of golang exec.Command program
问题
我有这样的代码:
func main() {
s := "foobar"
cmd := exec.Command("wc", "-l")
stdin, err := cmd.StdinPipe()
if err != nil {
log.Panic(err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Panic(err)
}
err = cmd.Start()
if err != nil {
log.Panic(err)
}
io.Copy(stdin, bytes.NewBufferString(s))
stdin.Close()
io.Copy(os.Stdout, stdout)
err = cmd.Wait()
if err != nil {
log.Panic(err)
}
}
它的输出是:
0
但是当我做一个简单的修改时:
func main() {
runWcFromStdinWorks("aaa\n")
runWcFromStdinWorks("bbb\n")
}
func runWcFromStdinWorks(s string) {
cmd := exec.Command("wc", "-l")
stdin, err := cmd.StdinPipe()
if err != nil {
log.Panic(err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Panic(err)
}
err = cmd.Start()
if err != nil {
log.Panic(err)
}
io.Copy(stdin, bytes.NewBufferString(s))
stdin.Close()
io.Copy(os.Stdout, stdout)
err = cmd.Wait()
if err != nil {
log.Panic(err)
}
}
它可以工作,但是为什么?它只是调用了一个方法,为什么第一个版本不起作用?
英文:
I have such code:
func main() {
s := "foobar"
cmd := exec.Command("wc", "-l")
stdin, err := cmd.StdinPipe()
if err != nil {
log.Panic(err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Panic(err)
}
err = cmd.Start()
if err != nil {
log.Panic(err)
}
io.Copy(stdin, bytes.NewBufferString(s))
stdin.Close()
io.Copy(os.Stdout, stdout)
err = cmd.Wait()
if err != nil {
log.Panic(err)
}
}
and its output is:
0
But when I will do simple modification:
func main() {
runWcFromStdinWorks("aaa\n")
runWcFromStdinWorks("bbb\n")
}
func runWcFromStdinWorks(s string) {
cmd := exec.Command("wc", "-l")
stdin, err := cmd.StdinPipe()
if err != nil {
log.Panic(err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Panic(err)
}
err = cmd.Start()
if err != nil {
log.Panic(err)
}
io.Copy(stdin, bytes.NewBufferString(s))
stdin.Close()
io.Copy(os.Stdout, stdout)
err = cmd.Wait()
if err != nil {
log.Panic(err)
}
}
It works, but why? Its just calling method why first version is not working?
答案1
得分: 4
在第一个示例中,字符串s
没有换行符,这导致wc -l
返回0。你可以通过以下方式观察到这种行为:
$ echo -n hello | wc -l
0
英文:
The string s
in the first example does not have a new line, which causes wc -l
to return 0. You can see this behavior by doing:
$ echo -n hello | wc -l
0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论