Reputation: 1057
Hi guys for some reason Wait() when I execute mysql command hangs for ever, does anyone know why? Here is my code.
// 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")
}
}
This function accomplishes everything and mysql imports the data into database but it never return from Wait() just freezes there even though is completed.
Upvotes: 1
Views: 4685
Reputation: 5786
The problem is that you haven't closed the stdin
pipe. MySQL will remain active until it is.
The fix is thus simple:
// Write data to pipe
io.WriteString(stdin, data)
stdin.Close()
fmt.Println("Importing " + x.DB + " to localhost...")
The fact that StdinPipe()
acts in this way is documented as such:
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.
Upvotes: 4