如何在Linux中高效等待RS232的CTS或DSR?

发布于 2024-12-28 13:45:29 字数 441 浏览 2 评论 0原文

目前,我正在通过以下方式读取串行端口的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泪眸﹌ 2025-01-04 13:45:29

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 in ioctl_list(4).

I have learned about this ioctl in this question:

Python monitor serial port (RS-232) handshake signals

冧九 2025-01-04 13:45:29

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文