Skip to content

Commit 75e7534

Browse files
committed
Fix 100% CPU usage issue
1 parent 9911acd commit 75e7534

File tree

2 files changed

+41
-4
lines changed

2 files changed

+41
-4
lines changed

pkg/terminal/lazycopy.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package terminal
2+
3+
import (
4+
"io"
5+
"time"
6+
)
7+
8+
const BackOffReadInitialSleepDuration = time.Millisecond
9+
const BackOffReadMaxSleepDuration = time.Millisecond * 16
10+
11+
// similar to io.Copy with sleep when no data is received
12+
func lazyCopy(dst io.Writer, src io.Reader) error {
13+
14+
buffer := make([]byte, 4096)
15+
16+
backOffDelay := BackOffReadInitialSleepDuration
17+
18+
for {
19+
size, err := src.Read(buffer)
20+
if size > 0 {
21+
if _, err := dst.Write(buffer[:size]); err != nil {
22+
return err
23+
}
24+
backOffDelay = BackOffReadInitialSleepDuration
25+
}
26+
if err != nil {
27+
return err
28+
}
29+
if size == 0 {
30+
// if there was no data to read, wait a little while before trying again
31+
time.Sleep(backOffDelay)
32+
backOffDelay = backOffDelay * 2
33+
if backOffDelay > BackOffReadMaxSleepDuration {
34+
backOffDelay = BackOffReadMaxSleepDuration
35+
}
36+
}
37+
}
38+
}

pkg/terminal/terminal.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package terminal
22

33
import (
44
"fmt"
5-
"io"
65
"os"
76
"os/exec"
87
"os/signal"
@@ -126,9 +125,9 @@ func (t *Terminal) Run() error {
126125
defer func() { _ = terminal.Restore(int(os.Stdin.Fd()), oldState) }() // Best effort.
127126

128127
// Copy stdin to the pty and the pty to stdout.
129-
go func() { _, _ = io.Copy(t.pty, os.Stdin) }()
130-
go func() { _, _ = io.Copy(os.Stdout, t.proxy) }()
131-
_, _ = io.Copy(t.proxy, t.pty)
128+
go func() { _ = lazyCopy(t.pty, os.Stdin) }()
129+
go func() { _ = lazyCopy(os.Stdout, t.proxy) }()
130+
_ = lazyCopy(t.proxy, t.pty)
132131
fmt.Printf("\r\n")
133132
return nil
134133
}

0 commit comments

Comments
 (0)