在 goroutine 调用 exec 后主线程不是 运行?

Main thread not running after goroutine calls exec?

我正在阅读 Go 中的 exec https://gobyexample.com/execing-processes,并尝试使用 goroutines 做同样的事情。

在下面的代码中,我试图让 Go 运行 ls,然后在主线程中打印一条成功消息。但是,它只打印 ls,而不打印成功消息。

怎么回事?

谢谢。

package main

import "syscall"
import "os"
import "os/exec"
import "fmt"

func main() {
    p := fmt.Println
    done := make(chan bool)
    binary, lookErr := exec.LookPath("ls")
    if lookErr != nil {
        panic(lookErr)
    }

    args := []string{"ls", "-a", "-l", "-h"}

    env := os.Environ()

    go func() {
        execErr := syscall.Exec(binary, args, env)
        if execErr != nil {
            panic(execErr)
        }
        done <- true
    }()

    <-done

    p("Done with exec")
}

这是输出:

Valeriys-MacBook-Pro:test valeriy$ go run test.go 
total 8
drwxr-xr-x  3 valeriy  staff    96B Dec 17 15:46 .
drwxr-xr-x  8 valeriy  staff   256B Dec 17 00:06 ..
-rw-r--r--  1 valeriy  staff   433B Dec 17 15:38 test.go

syscall.Exec 用调用的进程替换当前进程。

如果你想运行一个外部命令同时保持原来的程序运行ning,你需要使用exec.Command

顺便说一句,您包含的 link 确实说:

Sometimes we just want to completely replace the current Go process with another (perhaps non-Go) one.

如果你真的想使用 syscall 包,你可以使用 syscall.StartProcess 它执行 fork/exec 而不是普通的 exec。