在前面的例子中,我們看看產生外部進程。 當需要一個運行的Go進程可訪問的外部進程時,我們就可以這樣做。有時只是想用另一個(可能是非Go)完全替換當前的Go進程。可使用Go的經典exec函數來實現。
在下面的例子將執行ls命令。 Go需要一個我們想要執行的二進制的絕對路徑,所以將使用exec.LookPath來找到它(可能是/bin/ls)。

所有的示例代碼,都放在 F:\worksp\golang 目錄下。安裝Go編程環境請參考: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 {

    // `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 {

執行上面代碼,將得到以下輸出結果 -

此程序僅限在 Linux 類系統上執行。