2013-02-13 55 views
0

此程序是(我相信)select()(在Debian for ARM上)的直接應用程序。 XBEEDEVICE指向一個串行端口。串行端口存在,並且ic連接到設備。即使緩衝區中有數據,select()也會超時

問題是,即使有數據收到,select()也會返回0。我暫時註釋掉了最後的'else',程序打印出TIMEOUT,然後是遠程設備返回的字符串。

int main(int argc, char **argv) { 
    int fd, c, res, n; 
    struct termios oldtio, newtio; 
    char buf[255] = {0}; 

    fd_set input; 
    struct timeval timeout; 

    // define timeout 
    timeout.tv_sec = 5; 
    timeout.tv_usec = 0; 

    fd = open(XBEEDEVICE, O_RDWR | O_NOCTTY); 
    if(fd < 0){ 
    perror(XBEEDEVICE); 
    return(-1); 
    } 

    tcgetattr(fd, &oldtio); /* save current port settings */ 
    bzero(&newtio, sizeof(newtio)); 
    newtio.c_cflag = CRTSCTS | CS8 | CLOCAL | CREAD; 
    newtio.c_iflag = IGNPAR; 
    newtio.c_oflag = 0; 

    /* set input mode (non-canonical, no echo,...) */ 
    newtio.c_lflag = 0; 

    newtio.c_cc[VTIME] = 0; /* inter-character timer unused */ 
    newtio.c_cc[VMIN]  = 2; /* blocking read until 2 chars received */ 

    tcflush(fd, TCIFLUSH); 
    tcsetattr(fd, TCSANOW, &newtio); 

    // Sending +++ within 1 second sets the XBee into command mode 
    printf(" Sending +++\n"); 
    write(fd, "+++", 3); 

    n = select(fd, &input, NULL, NULL, &timeout); 

    if(n < 0) 
    printf("select() failed\n"); 
    else if(n == 0) 
    printf("TIMEOUT\n"); 
    //else{ 
    res = read(fd, buf, 250); 
    buf[res] = 0; 
    printf("Received: %s\n", buf); 
    //} 
    tcsetattr(fd, TCSANOW, &oldtio); 

    return(0); 
} 
+0

您應該爲您的問題添加更多標籤。 Stackoverflow有一個很好的系統來通知人們他們最喜歡的標籤,所以如果你添加更多相關標籤,他人會更容易找到你的問題... – 2013-02-13 03:23:21

回答

3

您應該初始化input以包含fd。這與FD_ZEROFD_SET宏完成:

FD_ZERO(&input); 
FD_SET(fd, &input); 

這必須每個select被調用之前的時間內完成完成。

select的第一個參數應該是fd+1。它是要檢查的範圍內的文件描述符的數量。由於範圍內的最大(且唯一)描述符編號爲fd,且最小值始終爲0,因此所討論的編號爲fd+1

+0

謝謝你,今晚我會試試。我試過fd + 1(但不是FD_ZERO()或FD_SET()),這並沒有什麼區別。 – 2013-02-13 13:04:34

+0

我已經添加了FD_ZERO()和FD_SET()調用,並將'fd'更改爲fd + 1',現在它可以工作。非常感謝你! – 2013-02-13 23:43:23

相關問題