通过打开和读取检测可用设备

时间:2012-11-08 18:15:21

标签: c linux

说我打开设备。

int fd,fd1;
fd_set readfds;
int maxfd;

fd = open("/dev/ttyUSB0");
if(fd<0) printf("device not available\n");//How can i Wait here until device becomes available?.. Also when it shows device not available it will just continue on doing select.
printf("device /dev/ttyUSB0 available\n"); 

fd1 = open("/dev/ttyUSB1");
if(fd<0) printf("device not available\n");//How can i Wait here until device becomes available?
printf("device /dev/ttyUSB1 available\n");

maxfd = MAX(fd,fd1)+1;

现在我将它们添加到fd_set;

while(1){

FD_SET(fd,&readfds);
FD_SET(fd1,&readfds);

select(maxfd, &readfds, NULL, NULL, NULL);

if(FD_ISSET(fd,&readfds){

// Read the device. If there is nothing to read then device has been removed or something happend.

}

if(FD_ISSET(fd1,&readfds){

// Read the device. If there is nothing to read then device has been removed or something happend.

}


}

现在,如何在设备可用时检查设备。假设我打开它时设备是否不可用。如何监控它以检查它何时被插入?我不想使用udev / libudev.h。

谢谢,

1 个答案:

答案 0 :(得分:1)

常见的方法是尝试写入设备中的某些数据并回读响应。如果预期响应则表示设备已连接,否则表示未连接。

例如,当扫描连接调制解调器的COM端口时,应将"ATE0\r"写入COM端口并返回调制解调器响应"OK"。这意味着调制解调器连接到该COM端口。

同样的想法适用于USB设备。只有协议更复杂,请求/响应数据在设备之间可能更复杂。