在前面的例子中,我们看看产生外部进程。 当需要一个运行的go进程可访问的外部进程时,我们就可以这样做。有时只是想用另一个(可能是非go)完全替换当前的go进程。可使用go的经典exec
函数来实现。
在下面的例子将执行ls
命令。 go需要一个我们想要执行的二进制的绝对路径,所以将使用exec.lookpath
来找到它(可能是/bin/ls
)。
所有的示例代码,都放在
f:\worksp\golang
目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html
execing-processes.go
的完整代码如下所示 -
package main
import "syscall"
import "os"
import "os/exec"
func main() {
// for our example we'll exec `ls`. go requires an
// absolute path to the binary we want to execute, so
// we'll use `exec.lookpath` to find it (probably
// `/bin/ls`).
binary, lookerr := exec.lookpath("ls")
if lookerr != nil {
panic(lookerr)
}
// `exec` requires arguments in slice form (as
// apposed to one big string). we'll give `ls` a few
// common arguments. note that the first argument should
// be the program name.
args := []string{"ls", "-a", "-l", "-h"}
// `exec` also needs a set of [environment variables](environment-variables)
// to use. here we just provide our current
// environment.
env := os.environ()
// here's the actual `syscall.exec` call. if this call is
// successful, the execution of our process will end
// here and be replaced by the `/bin/ls -a -l -h`
// process. if there is an error we'll get a return
// value.
execerr := syscall.exec(binary, args, env)
if execerr != nil {
panic(execerr)
}
}
执行上面代码,将得到以下输出结果 -
此程序仅限在 linux 类系统上执行。