I am trying to read from the Stdout of a command, but once every (approx.) 50 times it freezes.
func runProcess(process *exec.Cmd) (string, string, error) {
var stdout strings.Builder
var stderr string
process := exec.Command(programPath, params...)
go func() {
pipe, err := process.StderrPipe()
if err != nil {
return
}
buf, err := io.ReadAll(pipe)
if err != nil {
log.Warn("Error reading stderr: %v", err)
}
stderr = string(buf)
}()
pipe, err := process.StdoutPipe()
if err = process.Start(); err != nil {
return "", "", err
}
buf := make([]byte, 1024)
read, err := pipe.Read(buf) // it reads correctly from the pipe
for err == nil && read > 0 {
_, err = stdout.Write(buf[:read])
read, err = pipe.Read(buf) // this is where is stalls
}
if err = process.Wait(); err != nil {
return stdout.String(), stderr, err
}
return stdout.String(), stderr, nil
}
I've tried to use stdout, err := io.ReadAll(pipe) to read everything at once instead of reading chunks, but I get the same behaviour.
The program that is called seems to be executed successfully. Its logfile is created and it is complete. Plus, first time when I read from the pipe (before the loop), all the output is there. But inside the loop, when the .Read() is called for the second time and it should return an EOF (the output is smaller than 1024 bytes), it freezes.