大家好,当我执行 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/