I have a serial device connected via USB. I've opened the tty (/dev/ttyACM0) and wait for incoming messages which are read and processed, then I wait for the next message. The problem is if the usb device gets disconnected, my code does not detect this and essentially hangs.
One solution would be to check the return value of the read()
function, if it's 0 then use system("lsof ...")
to check whether it's still connected. This would work but it feels pretty clumsy to me. Is there a better way to detect device disconnection in c code?
Thanks to all those that responded.
I found several solutions to this: using stat()/fstat()
as described here 1. stat()
will return -1 with errno==ENOENT, and fstat()
will return stat.st_nlink=0 when the usb device is unplugged.
However, I think I'll go with the poll()
solution suggested by @IanAbbott. It feels a little more tightly coupled to what I want to do, though all the above solutions worked.