Home > Backend Development > Golang > How Can I Achieve Non-Blocking Character Input in Go?

How Can I Achieve Non-Blocking Character Input in Go?

DDD
Release: 2024-12-31 22:05:12
Original
968 people have browsed it

How Can I Achieve Non-Blocking Character Input in Go?

Non-Blocking Character Input in Go

Reading a character from standard input without pressing Enter can be achieved using Go's standard library and executing operating system commands.

For Windows users, a non-canonical input mode may be available using the syscall package. However, this approach is platform-dependent and may not be suitable cross-platform development.

UNIX-Based Solution

The provided solution works for UNIX-based systems and disables input buffering and character echoing:

package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    // disable input buffering
    exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run()
    // do not display entered characters on the screen
    exec.Command("stty", "-F", "/dev/tty", "-echo").Run()

    var b []byte = make([]byte, 1)
    for {
        os.Stdin.Read(b)
        fmt.Println("I got the byte", b, "("+string(b)+")")
    }
}
Copy after login

This program will repeatedly read a character from standard input until it is terminated. The cbreak mode disables line buffering, while the -echo flag prevents the entered character from being displayed on the screen.

Note:

This solution assumes that you are using a terminal emulator that supports non-canonical input mode. If your terminal does not support it, you may need to adjust the code accordingly.

The above is the detailed content of How Can I Achieve Non-Blocking Character Input in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template