linux下ttyUSB0设备开机、关闭、重起的自动检测c代码
#include sys/time.h>
#include time.h>
bool try2connect_ttyusb(void)
{
int file;
struct timeval time_ticks;
int past_closed = 0;
int time_closed = 0;
int time_closed_tmp,time_closed_tmp_pre;

for(;;)
{
gettimeofday(&time_ticks,NULL);
if(time_ticks.tv_usec 1000)break;//等待近似0ms的开始
file = open(DeviceName, O_RDWR | O_NOCTTY | O_NDELAY);
if(file > 0)
{
close(file);
}else return true;//有可能已等待1s了,已完成了重启,所以能够退出
}
time_closed_tmp_pre = 0;
for(;;)
{
file = open(DeviceName, O_RDWR | O_NOCTTY | O_NDELAY);
if(file > 0)
{
close(file);
if(past_closed)
{
fprintf(stderr,"\n%d个100ms过去了##",time_closed);
break;
}
}else past_closed = 1;
//gliethttp_20080327
gettimeofday(&time_ticks,NULL);
time_closed_tmp = time_ticks.tv_usec / (100*1000);
if(time_closed_tmp != time_closed_tmp_pre)
{
if(time_closed > 50)
{
fprintf(stderr,"\ntime out\n");
break;
}

#if 0
if(file 0)fprintf(stderr,"\nNO");
else
{
fprintf(stderr,"\nYES");
}
#endif
time_closed_tmp_pre = time_closed_tmp;
}
}
return (past_closed && (file > 0));
}


本文来自ChinaUnix博客,假如查看原文请点:http://blog.chinaunix.net/u1/38994/showart_509594.html