Skip to the content.

termios

termios 是 POSIX 标准中用于控制终端(TTY)设备 I/O 行为的接口,主要针对串行端口(如 UART、USB 转串口)以及伪终端(pty)等字符设备。以下几类项目通常需要使用 termios

1. 串口通信程序

2. 终端模拟器(Terminal Emulator)

3. 伪终端(PTY)管理工具

4. 系统级调试或监控工具

5. 自定义 REPL 或交互式解释器

6. 低层网络或协议仿真(通过串口或 loopback TTY)


典型 termios 操作包括:

termios 是 POSIX 标准定义的一套接口规范,其“源码”并非单一文件,而是由 C 标准库(如 glibc) 提供用户空间的封装函数(如 tcgetattr, tcsetattr),而底层功能则由 Linux 内核 实现。因此,它的实现分布在两个地方:


一、用户空间:glibc(或 musl 等 C 库)

这些库提供符合 POSIX 的 termios.h 头文件和函数封装。

二、内核空间:Linux 内核

真正的终端设备行为(如串口、pty 的设置)由内核实现,主要集中在:

关键文件:


总结

| 组件 | 作用 | 源码位置示例 | |————|————————–|———————————-| | glibc | 提供 tcgetattr 等函数 | glibc 源码中的 termios/ 目录 | | Linux 内核 | 实现底层 TTY 控制逻辑 | drivers/tty/, tty_ioctl.c | | 用户头文件 | 提供 struct termios | /usr/include/termios.h |

如果你是 Linux 内核工程师(如记忆所示),你可能更关注 内核中的实现,特别是 tty_ioctl.ctty_mode_ioctl()n_tty_ioctl_helper() 等函数如何处理 termios 的设置。

需要我展示 tcsetattr 如何从 glibc 调用到内核的完整路径吗?

似乎 api 就是这些

   - tcgetattr(fd, &termios) - Gets terminal attributes (using TCGETS/TCGETS2)
   - tcsetattr(fd, action, &termios) - Sets terminal attributes (using TCSETS/TCSETS2)
   - tcflush(fd, queue_selector) - Flushes data (using TCFLSH)
   - tcflow(fd, action) - Controls flow (using TCXONC)
   - tcdrain(fd) - Waits for output to drain (using TCSBRK)
   - tcsendbreak(fd, duration) - Sends break signal (using TCSBRK/TCSBRKP)
   - tcgetpgrp(fd) - Gets foreground process group (using TIOCGPGRP)
   - tcsetpgrp(fd, pgrp) - Sets foreground process group (using TIOCSPGRP)
   - tcgetsid(fd) - Gets session ID (using TIOCGSID)

其实,最精确的实现在 drivers/tty/tty_io.c 中

本站所有文章转发 CSDN 将按侵权追究法律责任,其它情况随意。