Go exec.Command(...).Wait() 永远挂起

标签 go

大家好,当我执行 mysql 命令时,由于某种原因 Wait() 永远挂起,有人知道为什么吗? 这是我的代码。

// Import imports data into Local database
func (x MySQL) Import(data string, opt LocalDb) {
    var stderr bytes.Buffer
    cmd := exec.Command("mysql", x.importOptions(opt)...)
    // Set < pipe variable
    stdin, err := cmd.StdinPipe()
    errChk(err)

    cmd.Stderr = &stderr
    cmd.Start()

    // Write data to pipe
    io.WriteString(stdin, data)
    fmt.Println("Importing " + x.DB + " to localhost...")

    // Log mysql error
    if err := cmd.Wait(); err != nil {
        log.Fatal(stderr.String())
    } else {
        fmt.Println("Importing complete")
    }
}

此函数完成所有操作,mysql 将数据导入数据库,但它永远不会从 Wait() 返回,即使已完成也只是卡住在那里。

最佳答案

问题是您还没有关闭 stdin 管道。 MySQL 将保持事件状态,直到它结束。

修复非常简单:

// Write data to pipe
io.WriteString(stdin, data)
stdin.Close()
fmt.Println("Importing " + x.DB + " to localhost...")

StdinPipe() 以这种方式运行的事实记录如下:

StdinPipe returns a pipe that will be connected to the command's standard input when the command starts. The pipe will be closed automatically after Wait sees the command exit. A caller need only call Close to force the pipe to close sooner. For example, if the command being run will not exit until standard input is closed, the caller must close the pipe.

关于Go exec.Command(...).Wait() 永远挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40697126/

相关文章:

go - GO 中的工厂模式(包装器)

json - 在 go 中,什么是 json.Unmarshal 最大深度?

go - 可以在生产中使用 golang pprof 而不影响性能吗?

go - 在 Go 语言中,函数末尾缺少 return

json - 如何将相同值编码和解码为具有不同类型的结构?

go - sync.WaitGroup和嵌套循环

go - 滑行更新清空 glide.lock

go - 为什么在 Go 语言中使用 select 语句

mysql - 如何在 GO MYSQL 中构造具有许多相似参数的 sql?

go - 无法检测到 Kubernetes 中的 tcp 服务没有带有 golang 应用程序的 pod