Skip to content

Instantly share code, notes, and snippets.

@mrnugget
Created March 16, 2014 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrnugget/9582788 to your computer and use it in GitHub Desktop.
Save mrnugget/9582788 to your computer and use it in GitHub Desktop.
Use `stty` to change the operation mode of the terminal to disable line-buffering and non-echoing of typed characters. This lets us read one byte from STDIN. This version is currently tested with OS X
package main
import (
"bytes"
"fmt"
"log"
"os"
"os/exec"
)
var originalSttyState bytes.Buffer
func getSttyState(state *bytes.Buffer) (err error) {
cmd := exec.Command("stty", "-g")
cmd.Stdin = os.Stdin
cmd.Stdout = state
return cmd.Run()
}
func setSttyState(state *bytes.Buffer) (err error) {
cmd := exec.Command("stty", state.String())
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
return cmd.Run()
}
func main() {
err := getSttyState(&originalSttyState)
if err != nil {
log.Fatal(err)
}
defer setSttyState(&originalSttyState)
setSttyState(bytes.NewBufferString("cbreak"))
setSttyState(bytes.NewBufferString("-echo"))
var b []byte = make([]byte, 1)
for {
os.Stdin.Read(b)
fmt.Printf("Read character: %s\n", b)
}
}
@vegarsti
Copy link

Thank you for this! Following along to this text editor tutorial in C, and didn't realize you could set settings using stty.

@mrnugget
Copy link
Author

Thank you for commenting on a 7 year old gist 😄

@vegarsti
Copy link

😂

@glommer
Copy link

glommer commented Jun 6, 2023

oh, but I can do better! I can comment on a 9 year old gist!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment