Created
March 16, 2014 12:54
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Thank you for commenting on a 7 year old gist 😄
😂
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
Thank you for this! Following along to this text editor tutorial in C, and didn't realize you could set settings using stty.