在前面的例子中,我們看看產(chǎn)生外部進(jìn)程。 當(dāng)需要一個運(yùn)行的Go進(jìn)程可訪問的外部進(jìn)程時,我們就可以這樣做。有時只是想用另一個(可能是非Go)完全替換當(dāng)前的Go進(jìn)程??墒褂肎o的經(jīng)典exec函數(shù)來實現(xiàn)。
在下面的例子將執(zhí)行ls命令。 Go需要一個我們想要執(zhí)行的二進(jìn)制的絕對路徑,所以將使用exec.LookPath來找到它(可能是/bin/ls)。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請參考:http://www.yiibai.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)
}
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
此程序僅限在 Linux 類系統(tǒng)上執(zhí)行。