开发者

Open /dev/ttyUSB* when it becomes present

I have a program that will always be running when the computer is. It interfaces with serial over USB device. At times the device may not be present when the computer is on.

My question is a good method to acknowledge when the device file becomes present. I could make开发者_高级运维 a infinite loop that continuously checks for the file assuming I know what its name will be then break when it gets an fd. But is there a better way than this?

Additionally, assuming the device gets unplugged while the program is running my fd now becomes invalid. Is some event or error thrown when this happens so I can again begin checking until the device file is present again?

I read from the fd using a select loop.


On Linux your application can be notified when a device is plugged in and or removed by using udev.

For a great example take a look at this notifier: udev-notify

The libudev API will allow you to listen to kernel events and be notified when a device is available or when it gets removed and then you can decide to do when such events happen.


Historically, the solution of polling (a loop that determines if said "file" exists at some interval) would be the "best" one. If you're using modern Linux (2.6.12+ but you didn't specify), you can use inotify which probably does exactly what you want -- monitor a directory for the creation of a file (IN_CREATE). The Wikipedia article to which I linked gives a very good overview and helpful links.

The part where it becomes unplugged is tricky. When a file is deleted in *nix (dating back to forever-ago), its file descriptors are still valid. Therefore I would guess that extern int errno; may be your solution; your post was tagged with "C" so there is nothing to "throw" but if you check this when your read (or whatever) call fails, you can gain insight.

Also check out libudev, which is of course more specific to devices rather than the general "everything is a file" philosophy of *nix.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜