Reputation: 11697
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?
Upvotes: 0
Views: 171
Reputation: 13910
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
Upvotes: 4