dsl2014
dsl2014
2015-11-19 06:35
浏览 151
已采纳

Golang exec.Command程序的奇怪行为

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
")
        runWcFromStdinWorks("bbb
")
}

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条回答 默认 最新

  • doudu35999489610
    doudu35999489610 2015-11-19 06:45
    已采纳

    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
    
    点赞 评论

相关推荐