Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15496171
  • 博文数量: 2005
  • 博客积分: 11986
  • 博客等级: 上将
  • 技术积分: 22535
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-17 13:56
文章分类

全部博文(2005)

文章存档

2014年(2)

2013年(2)

2012年(16)

2011年(66)

2010年(368)

2009年(743)

2008年(491)

2007年(317)

分类: LINUX

2008-03-27 11:35:58

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));
}

阅读(4735) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~