我正在阅读 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
用调用的进程替换当前进程。
如果你想在保持原程序运行的同时运行外部命令,你需要使用exec.Command
顺便说一句,您包含的链接确实说:
Sometimes we just want to completely replace the current Go process with another (perhaps non-Go) one.
如果你真的想使用 syscall
包,你可以使用 syscall.StartProcess
,它执行 fork/exec 而不是普通的 exec。
关于multithreading - goroutine调用exec后主线程不运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47860671/