dongmi5607 2017-12-18 00:06
浏览 43
已采纳

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

I was reading about exec in Go https://gobyexample.com/execing-processes, and tried to do the same using goroutines.

In the following code, I'm trying to make Go run ls, then print a success message in the main thread. However, it's only printing the ls, but not the success message.

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
  • 写回答

1条回答 默认 最新

  • dpylt7626401 2017-12-18 00:14
    关注

    syscall.Exec replaces the current process with the one invoked.

    If you want to run an external command while keeping the original program running, you need to use 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.

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测