如何让read函数不挂起?

发布于 2024-09-29 01:30:09 字数 318 浏览 0 评论 0原文

我正在使用 socat 创建一个虚拟串行端口:

socat PTY,link=/dev/ttySV0,echo=1 PTY,link=/dev/ttySV1,echo=1

在用 C++ 编写的程序中,我打开 ttySV1 端口并开始读取。

读取函数有一段时间了,但问题是读取函数挂起,直到我将数据发送到端口。您知道如何使 taht 函数在缓冲区中没有数据时不挂起并退出吗?

编辑:我使用以下方式将数据发送到端口:

echo [data] > /dev/ttySV0

I'm using socat to create a virtual serial port with:

socat PTY,link=/dev/ttySV0,echo=1 PTY,link=/dev/ttySV1,echo=1

The in my program written in C++, I open the ttySV1 port and start to read.

The read function is in a while, but the problem is that the read function hangs until I send data to the port. Do you know how to make the taht function not to hang and just exit if there is no data in the buffer?

EDIT: I send data to the port using:

echo [data] > /dev/ttySV0

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

靑春怀旧 2024-10-06 01:30:09

您还可以根据您运行的操作系统使用系统读取功能。
详细信息应该在 man(3) 下阅读。

您必须使用 fnctl 设置 O_NONBLOCK。如果管道/ FIFO 当前为空,这会导致读取失败。我检查了 Linux 的手册页,但它们在大多数基于 POSIX 的系统中应该有类似的行为。

You could also use a system read function depending on the operating system you are running.
The details should be under man (3) read.

You would have to set O_NONBLOCK using fnctl. This should cause your read to fail if the pipe / FIFO is currently empty. I checked the man pages for Linux but their should be similar behaviors in most POSIX based systems.

云之铃。 2024-10-06 01:30:09

一种方法是使用 select() 方法查看是否有数据要读取。 这个或在谷歌上找到的其他东西(我搜索了“bsd套接字选择”)应该引导您走上正确的道路。

One way is to use the select() method to see if there is data to be read. This or something else found on google (I searched for "bsd sockets select") should lead you down the right path.

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