Home >Backend Development >Golang >How to set timeout for bufio scanner that scans in a loop?
I am using golang to start a process and monitor the output. The process will run for a long time and I need to be able to send a signal to end it.
I have the following code which works fine in most cases. But for some reasons, the process may have no output, and the for loop will be blocked by the scan()
method and cannot receive messages from processfinishchan
.
Is there an easy way to set a timeout for the scan()
method? I tried a solution by running scan()
in another goroutine and using another select to receive from the new goroutine and timeout channel, but given the outer for
loop, does Will more and more goroutines be blocked by scan
? p>
// code that start the process... scanner := bufio.NewScanner(stdout) for { select { case <-processFinishChan: // send to this channel to terminate the process log.Println("Killing Process") err := cmdObject.Process.Kill() if err != nil { log.Printf("Error Killing: %v", err) } else { return } default: // default case, read the output of process and send to user. if !scanner.Scan() && scanner.Err() == nil { // reach EOF return } m := scanner.Bytes() WSOutChanHolder.mu.Lock() for _, ch := range WSOutChanHolder.data { ch <- m } WSOutChanHolder.mu.Unlock() } }
Assuming that stdout
is the result of cmdobject.stdoutpipe()
, then the reader should be in Closes the reader while waiting after the process exits and interrupts any reads in progress.
wait will close the pipe after seeing the command exit, so most callers will not need to close the pipe themselves.
So, we need to kill the process in a separate goroutine and then wait after killing the process to watch it happen and close the reader.
// code that start the process... scanner := bufio.NewScanner(stdout) go func() { <-processFinishChan: // send to this channel to terminate the process log.Println("Killing Process") err := cmdObject.Process.Kill() if err != nil { log.Printf("Error Killing: %v", err) } cmdObject.Wait() } () for { // default case, read the output of process and send to user. if !scanner.Scan() && scanner.Err() == nil { // reach EOF return } m := scanner.Bytes() WSOutChanHolder.mu.Lock() for _, ch := range WSOutChanHolder.data { ch <- m } WSOutChanHolder.mu.Unlock() }
The above is the detailed content of How to set timeout for bufio scanner that scans in a loop?. For more information, please follow other related articles on the PHP Chinese website!