获取Linux系统上所有可用串行端口/设备列表的正确方法是什么?
换句话说,当我迭代/dev/
中的所有设备时,我如何以classic 的方式判断哪些设备是串行端口,也就是那些通常支持波特率和RTS/CTS流量控制的设备?
解决方案将用C编码.
我这样问是因为我使用的第三方库显然是错误的:它似乎只在/dev/ttyS*
上迭代.问题是,例如,USB上有串行端口(由USB-RS232适配器提供),这些端口列在/dev/ttyUSB*下.读了这Serial-HOWTO at Linux.org个名字,我觉得随着时间的推移,还会有其他的名字空间.
所以我需要找到检测串行设备的官方方法.问题是似乎没有任何记录,或者我找不到.
我想其中一种方法是打开/dev/tty*
中的所有文件,并调用仅在串行设备上可用的特定ioctl()
.不过,这是一个好的解决方案吗?
使现代化
hrickards建议查看"setserial"的来源.
首先,它打开一个具有以下功能的设备:
fd = open (path, O_RDWR | O_NONBLOCK)
然后它调用:
ioctl (fd, TIOCGSERIAL, &serinfo)
如果这个调用没有返回错误,那么显然是串行设备.
我在100中找到了类似的代码,建议也添加O_NOCTTY
选项.
There is one problem with this approach, though:
When I tested this code on BSD Unix (that is, Mac OS X), it worked as well. However, serial devices that are provided through Bluetooth cause the system (driver) to try to connect to the Bluetooth device, which takes a while before it'll return with a timeout error. This is caused by just opening the device. And I can imagine that similar things can happen on Linux as well - ideally, I should not need to open the device to figure out its type. I wonder if there's also a way to invoke ioctl
functions without an open, or open a device in a way that it does not cause connections to be made?
我该怎么办?