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.

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

报告相同问题?

悬赏问题

  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页