Skip to content

Instantly share code, notes, and snippets.

@yunginnanet
Last active December 12, 2022 00:01
Show Gist options
  • Save yunginnanet/6440539a6653b96ccf5afb8deb738204 to your computer and use it in GitHub Desktop.
Save yunginnanet/6440539a6653b96ccf5afb8deb738204 to your computer and use it in GitHub Desktop.
get current baud rate of tty/serial device in linux via ioctl syscall
package main
import (
"os"
"strconv"
"golang.org/x/sys/unix"
)
func getBaudRate(name string) (int, error) {
fd, err := unix.Open(name, unix.O_RDONLY|unix.O_NONBLOCK|unix.O_LARGEFILE, 0)
if err != nil {
return 0, err
}
term, err := unix.IoctlGetTermios(fd, unix.TCGETS2)
unix.Close(fd)
if err != nil {
return 0, err
}
return int(term.Ispeed), nil
}
func main() {
target := "/dev/tty0"
if len(os.Args) > 1 {
target = os.Args[1]
}
res, err := getBaudRate(target)
if err != nil {
println(err.Error())
return
}
println(target + " baud rate: " + strconv.Itoa(res))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment