exec.Run is an easy-to-use a wrapper for os.ForkExec, which is itself
a wrapper for syscall.ForkExec.
Use exec.Run. Here's a snippet of code that reads the stdout of a
command into a bytes.Buffer:
p, err := exec.Run(cmd, args, nil, "",
exec.DevNull, exec.Pipe, exec.PassThrough)
if err != nil {
return
}
b := bytes.NewBuffer([]byte{})
_, err = b.ReadFrom(p.Stdout)
if err != nil {
return
}
err = p.Close()
if err != nil {
return
}
Andrew
> b := bytes.NewBuffer([]byte{})
could more simply be:
var b bytes.Buffer
Andrew
/bin/sh -c "cd / && ls"
Also, the first argument to args should be the name of the command.
(analogous to argv[0] being the name of the running program)
Here's a working program:
package main
import (
"fmt"
"exec"
"bytes"
)
func main() {
cmd := "/bin/sh"
args := []string{cmd, "-c", "ls passwd"}
dir := "/etc"
p, err := exec.Run(cmd, args, nil, dir,
exec.DevNull, exec.Pipe, exec.PassThrough)
if err != nil {
return
}
var b bytes.Buffer
_, err = b.ReadFrom(p.Stdout)
if err != nil {
return
}
err = p.Close()
if err != nil {
return
}
fmt.Println(b.String())
Then you should populate the 'env' argument to Run with the relevant
environment variables. Or write a shell script which does the same.
Andrew