Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I want to be able to list every port in a computer and connect to the last serial port available. If I have com1, 2, 3, it should connect to port 3, if it is disconnected, the app should connect to port 2 and so on.
If someone could give me an example, I would greatly appreciate it.
Posted

1 solution

With recent Linux kernels, there will be the directory /dev/serial containing links to the serial devices. This contains only links to existing devices.

Classic serial ports are linked as /dev/ttySx and USB to serial adapters are linked as /dev/ttyUSBx where x is enumerating the ports starting at zero.

Especially the /dev/ttySx links may be also present for not existing ports. So these must be checked. This can be done on the command line using
setserial -g /dev/ttySx


To check the existance programmatically, open the device and issue an ioctl TIOCGSERIAL request:
int fd = open(device, O_RDWR | O_NONBLOCK);
if (fd != -1)
{
    serial_struct info;
    // Port exists when this returns zero
    ioctl(fd, TIOCGSERIAL, &info);
    close(fd);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900