【发布时间】:2018-12-21 08:56:47
【问题描述】:
我目前正在尝试使用串行端口与外部设备通信,它工作得很好……如果设备已连接。但是,由于不能保证它是(并且我有多个串行端口可供选择),如果我可以使用 VMIN=0 / VTIME>0 定时读取来探测端口(通常会阻止我的应用程序),那将是理想的防止无限期阻塞,以防设备在运行期间分离)。
这是我打开串行端口并将其设置为非规范模式的代码。但是即使我将 VTIME 设置为 5(应该是半秒)并将 VMIN 设置为 0(以便超时立即开始),如果没有连接设备,read() 也会无限期地阻塞。
int32_t OpenDevice(char* device)
{
if (access(device, R_OK | W_OK))
{
LOG(Log_Error, "%s() access(): %s", __func__, strerror(errno));
goto ERR_ACCESS;
}
int32_t fd = open(device, O_RDWR | O_NOCTTY);
if (fd == -1)
{
LOG(Log_Error, "%s() open(): %s", __func__, strerror(errno));
goto ERR_OPEN;
}
struct termios tios;
if (tcgetattr(fd, &tios))
{
LOG(Log_Error, "%s() tcgetattr(): %s", __func__, strerror(errno));
goto ERR_GETATTR;
}
cfmakeraw(&tios);
if (cfsetspeed(&tios, B115200))
{
LOG(Log_Error, "%s() cfsetspeed(): %s", __func__, strerror(errno));
goto ERR_SETSPEED;
}
tios.c_cflag |= CLOCAL | CREAD;
tios.c_cflag &= ~CRTSCTS;
tios.c_cc[VMIN] = 0;
tios.c_cc[VTIME] = 5;
if (tcsetattr(fd, TCSANOW, &tios))
{
LOG(Log_Error, "%s() tcsetattr(): %s", __func__, strerror(errno));
goto ERR_SETATTR;
}
struct termios tios_new;
tcgetattr(fd, &tios_new);
if (memcmp(&tios_new, &tios, sizeof(tios)))
{
LOG(Log_Error, "%s() failed to set attributes", __func__);
goto ERR_SETATTR;
}
return fd;
ERR_SETATTR:
ERR_SETSPEED:
ERR_GETATTR:
close(fd);
ERR_OPEN:
ERR_ACCESS:
return -1;
}
我不知道这是否重要,但我的应用程序不是在 PC 上运行,而是在具有 Cortex-A9 双核 CPU 的 Cyclone V SoC(来自 Altera/Intel)上运行。使用的驱动程序是 CONFIG_SERIAL_ALTERA_UART,它创建了几个 /dev/ttyAL 设备。操作系统本身是来自 Altera 的 git 存储库的版本,已经包含 PREEMPT_RT 补丁集 (rel_socfpga-4.1.22-ltsi-rt_16.10.02_pr)。
PS: 我知道我可以只使用 select() 并称之为一天,但我更愿意让我的代码保持简单,而不是为了获得超时而增加一堆开销。
提前感谢您对此问题的任何建议。
【问题讨论】:
-
使用 select() 是正确的做法,使用 select() 你的代码不会更复杂,问题不在于那个,它没有代码工作; )
-
@bruno 当然,我知道我的代码可以与 select() 一起正常工作,但让我烦恼的是 read() 超时不像 tcsetattr() 文档中描述的那样工作。我的代码应该工作,但它没有,我不知道为什么。
-
@FelixG:发布此问题的位置是linux-serial 邮件列表 (archives),标题为
altera-uart: VMIN=0, VTIME>0 read blocks indefinitely if no connection或类似名称,由 Tobias Klauser 抄送。 -
@Nominal Animal:感谢您的建议,我会这样做的。我当然会用任何新信息更新此线程,以便其他面临此问题的人更容易找到。
-
@sawdust:很有趣,所以我想这不是司机的错。
标签: c linux serial-port termios