如何在Linux中高效等待RS232的CTS或DSR?
目前,我正在通过以下方式读取串行端口的 CTS 和 DSR 信号:
bool get_cts(int fd) {
int s;
ioctl(fd, TIOCMGET, &s);
return (s & TIOCM_CTS) != 0;
}
现在我想等到 get_cts()
返回 true。我认为简单的循环不是最好的解决方案(因为它非常消耗资源)。
void wait_cts(int fd) {
while(1) {
if(get_cts(fd)) {
return;
}
}
}
在Linux上使用C或C++有更好的解决方案吗? (我无法使用任何硬件流控制,因为我根本不需要串行数据线。)
Currently, I'm reading the CTS and DSR signals of a serial port in the following way:
bool get_cts(int fd) {
int s;
ioctl(fd, TIOCMGET, &s);
return (s & TIOCM_CTS) != 0;
}
Now I'd like to wait until get_cts()
returns true. A simple loop isn't the best solution I think (as it's extremely resource-intensive).
void wait_cts(int fd) {
while(1) {
if(get_cts(fd)) {
return;
}
}
}
Is there any better solution using C or C++ on Linux? (I cannot use any hardware flow control as I don't need the serial data lines at all.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ioctl TIOCMIWAIT 会阻塞,直到一组给定的信号发生变化。
遗憾的是,这个 ioctl 没有记录在
tty_ioctl(4)
页面或ioctl_list(4)
中。我在这个问题中了解了这个ioctl:
Python监视串口(RS-232)握手信号
There is the ioctl
TIOCMIWAIT
which blocks until a given set of signals change.Sadly this ioctl is not documented in the
tty_ioctl(4)
page nor inioctl_list(4)
.I have learned about this ioctl in this question:
Python monitor serial port (RS-232) handshake signals
select 系统调用适用于此类应用程序。您可以做其他工作,或者睡觉,然后定期检查 FD_SET 的状态。如果您的程序除了获取数据之外什么也不做,那么对于您正在做的事情来说,它甚至可能是矫枉过正的。
The select system call is meant for applications like that. You can do other work, or sleep, then periodically check the status of the FD_SET. It might even be overkill for what you are doing, if your program does nothing else but grab data.