Sunday, 15 April 2012

go - How to connect several pipe command in slice -



go - How to connect several pipe command in slice -

i have check link how connect 2 pipe command below code.

func main() { c1 := exec.command("ls") c2 := exec.command("wc", "-l") c2.stdin, _ = c1.stdoutpipe() c2.stdout = os.stdout _ = c2.start() _ = c1.run() _ = c2.wait() }

but have several command more 2. command run c1 | c2 | c3 | c4 | c5, , these commands set in slice([](*exec.cmd)).

question: how can loop piece , execute command sequence , final result? thanks.

you have doing currently, except have loops. here total illustration nil more own illustration case:

package main import ( "os" "os/exec" ) func main() { var err error // store error during processing. should check errors , handle them. that's not option. var commands []*exec.cmd // piece store commands. // own commands commands = append(commands, exec.command("ls")) commands = append(commands, exec.command("wc", "-l")) // connect each command input output of previous command (starting sec command, obviously) := 1; < len(commands); i++ { commands[i].stdin, err = commands[i - 1].stdoutpipe() if err != nil { panic(err) } } commands[len(commands)-1].stdout = os.stdout // lastly command output connected standard output // start each command. note reverse order isn't mandatory, have avoid runing first command := len(commands) - 1; > 0; i-- { err = commands[i].start() if err != nil { panic(err) } } // run first command commands[0].run() // wait each subsequent command finish := 1; < len(commands); i++ { err = commands[i].wait() if err != nil { panic(err) } } }

go

No comments:

Post a Comment