我正在使用Linux中的termios api与串行设备通信。我正在尝试检测设备是否已断开连接,以便在超时后尝试重新连接。我有以下示例代码:
while(1)
{
FD_ZERO(&rfds);
FD_SET(tty_fd, &rfds);
// have tried checking fcntl(tty_fd, F_GETFL); too
// Blocking call to wait until we have data
select(tty_fd+1, &rfds, NULL, NULL, NULL);
// While we have data, collect it
while (read(tty_fd, &c, 1)>0 && bytesRead++<200)
{
serialBuffer.push_back(c);
}
bytesRead = 0;
// Try to parse it
BufferParse();
}
在ttyUSB设备物理断开连接后,我实际上没有看到select()或fcntl返回错误值(-1)。当然,我可以检查/dev/中的文件是否存在,但我希望有更好的解决方案。
非常感谢您的建议,谢谢!
发布于 2016-01-22 19:35:58
首先值得一提的是,串行usb的行为如下:
在usb设备上,拔出的断开连接称为
@disconnect:当接口不再可访问时调用,通常是因为其设备已(或正在被)断开连接或正在卸载驱动程序模块。
在我们的例子中,它是usb_serial_disconnect(结构usb_interface *接口)
它调用串行(Usb_serial_console_disconnect),它调用tty_hangup ...诸若此类。
你可以从这里开始关注chain:http://lxr.free-electrons.com/source/drivers/usb/serial/usb-serial.c#L1091
简而言之,这将导致以下经典方式:
pselect表示文件描述符已准备就绪,ioctl(fd,FIONREAD,& len )返回零len。
这就是你拔出设备的原因。
汇总(从您的代码派生):
while(1)
{
FD_ZERO(&rfds);
FD_SET(tty_fd, &rfds);
// have tried checking fcntl(tty_fd, F_GETFL); too
// Blocking call to wait until we have data
int ready = select(tty_fd + 1, &rfds, NULL, NULL, NULL);
if(ready && FD_ISSET(tty_fd, &rfds)) {
size_t len = 0;
ioctl(tty_fd, FIONREAD, &len);
errsv = errno;
if(len == 0)
{
printf("prog_name: zero read from the device: %s.", strerror(errsv));
/* close fd and cleanup or reconnect etc...*/
exit(EXIT_FAILURE);
}
// While we have data, collect it
while (read(tty_fd, &c, 1)>0 && bytesRead++<200)
{
serialBuffer.push_back(c);
}
bytesRead = 0;
// Try to parse it
BufferParse();
}
}
遗憾的是,您没有说明您使用的是哪种设备。
如果您的设备能够进行RTS/CTS流控制,那么也可以检测换行。
https://stackoverflow.com/questions/34170350
复制相似问题