I have a golang app which needs to listen for input on stdin - not as a command line utility but to keep running and listening. The following code, slightly edited down, works but has very high CPU load when 'idle' - and I am not sure why - nor clear how this could be done better. So I need the same functionality without the CPU load! (this is part of an authentication handler for ejabberd)
bioIn := bufio.NewReader(os.Stdin)
bioOut := bufio.NewWriter(os.Stdout)
var err error
var success bool
var length uint16
var result uint16
for {
binary.Read(bioIn, binary.BigEndian, &length)
buf := make([]byte, length)
r, _ := bioIn.Read(buf)
if r == 0 {
continue
}
if err == nil {
data := strings.Split(string(buf), ":")
// I have code to handle the incoming data here...
} else {
success = false
}
length = 2
binary.Write(bioOut, binary.BigEndian, &length)
if success != true {
result = 0
} else {
result = 1
}
binary.Write(bioOut, binary.BigEndian, &result)
bioOut.Flush()
}
ANSWER:
I added a short sleep as suggested and this has worked a charm; didn't need to be long and no noticeable impact on the authentication the service is providing. With the reassurance incoming data is buffered this is perfect fix. Thanks all.
r, _ := bioIn.Read(buf)
if r == 0 {
time.Sleep(25 * time.Millisecond)
continue
}