Go執行過程範例


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

所有的範例程式碼,都放在 F:\worksp\golang 目錄下。安裝Go程式設計環境請參考:/2/23/798.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 類系統上執行。