2010-03-18 49 views

回答

3

嘗試使用select。這將適用於TCP和UDP套接字。只是另一種方式來做和Len的答案一樣的事情,但不是爲套接字上的所有recv操作設置超時時間,而是可以根據調用的基礎設置超時時間長度。

#include <errno.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/time.h> 

int 
input_timeout (int filedes, unsigned int seconds) 
{ 
    fd_set set; 
    struct timeval timeout; 

    /* Initialize the file descriptor set. */ 
    FD_ZERO (&set); 
    FD_SET (filedes, &set); 

    /* Initialize the timeout data structure. */ 
    timeout.tv_sec = seconds; 
    timeout.tv_usec = 0; 

    /* select returns 0 if timeout, 1 if input available, -1 if error. */ 
    return TEMP_FAILURE_RETRY (select (FD_SETSIZE, 
             &set, NULL, NULL, 
             &timeout)); 
} 

int 
main (void) 
{ 
    fprintf (stderr, "select returned %d.\n", 
      input_timeout (STDIN_FILENO, 5)); 
    return 0; 
}