简体   繁体   English

goroutine调用exec后主线程未运行?

[英]Main thread not running after goroutine calls exec?

I was reading about exec in Go https://gobyexample.com/execing-processes , and tried to do the same using goroutines. 我在Go https://gobyexample.com/execing-processes中阅读了有关exec的内容,并尝试使用goroutines做同样的事情。

In the following code, I'm trying to make Go run ls , then print a success message in the main thread. 在以下代码中,我试图使Go运行ls ,然后在主线程中打印成功消息。 However, it's only printing the ls, but not the success message. 但是,它仅显示ls,而不显示成功消息。

What's going on? 这是怎么回事?

Thanks. 谢谢。

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")
}

Here's the output: 这是输出:

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 replaces the current process with the one invoked. syscall.Exec将当前进程替换为被调用的进程。

If you want to run an external command while keeping the original program running, you need to use exec.Command 如果要在保持原始程序运行的同时运行外部命令,则需要使用exec.Command

By the way, the link you included does say: 顺便说一句,您包含的链接确实显示:

Sometimes we just want to completely replace the current Go process with another (perhaps non-Go) one. 有时,我们只想用另一个(也许是非Go)进程完全替换当前的Go进程。

If you really want to use the syscall package, you can use syscall.StartProcess which does a fork/exec as opposed to a plain exec. 如果您确实要使用syscall程序包,则可以使用syscall.StartProcess来执行fork / exec而不是普通exec。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM