问题
Please let me know if there is any API, system call, function (in Linux) which I can use my C program to detect a COM port dynamically, i.e., whenever a USB modem dongle is inserted in the port I will be able to detect that COM port using the API, or system call, or function in my C program.
回答1:
Depending on your modem, USB serial port device may show up as /dev/ttyUSBn
or /dev/ttyACMn
, where n
is some number starting from 0
.
You can configure udev
rule to automatically react on device being inserted or removed.
If you want to do it on your own in C, you need to make use of netlink(7)
sockets. If you don't want to fiddle with them, probably easier approach is to simply use utility udevadm
provided by udev package (udevadm is using netlink
internally), something like that:
udevadm monitor --kernel
If you are going to use it in your C program, simply call it in pipe like this:
stdbuf -o0 udevadm monitor --kernel
and setup select
loop, so it can react immediately. Wrapping in stdbuf
is necessary to avoid buffering provided by udevadm.
回答2:
In Linux the serial ports aren't called COMx. They (real serial ports) are generally named /dev/ttySx
where x is a number, starting at 0 for COM1, 1 for COM2, etc.
If you want a list, you should look in /dev
for ttyS
devices.
Here is a very detailed page for serial port programming on Linux:
- Serial Programming HOWTO
- Serial HOWTO
Finally, note that a quick Google search goes a long way for general questions like this!
来源:https://stackoverflow.com/questions/15779978/com-port-detection-in-linux