#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
int main()
{
char name[20];
fd_set input_set;
struct timeval timeout;
int ready_for_reading = 0;
int read_bytes = 0;
/* Empty the FD Set */
FD_ZERO(&input_set);
/* Listen to the input descriptor */
FD_SET(0, &input_set);
/* Waiting for some seconds */
timeout.tv_sec = 10; // 10 seconds
timeout.tv_usec = 0; // 0 milliseconds
/* Invitation for the user to write something */
printf("Enter Username: (in 15 seconds)\n");
printf("Time start now!!!\n");
/* Listening for input stream for any activity */
ready_for_reading = select(1, &input_set, NULL, NULL, &timeout);
/* Here, first parameter is value of the socket descriptor + 1 (STDIN descriptor is 0, so
* 0 +1 = 1)
* in the set, second is our FD set for reading,
* third is the FD set in which any write activity needs to updated, which is not required
* in this case. Fourth is timeout
*/
if (ready_for_reading == -1) {
/* Some error has occured in input */
printf("Unable to read your input\n");
return -1;
} else {
if (ready_for_reading) {
read_bytes = read(0, name, 19);
printf("Read, %d bytes from input : %s \n", read_bytes, name);
} else {
printf(" 10 Seconds are over - no data input \n");
}
}
return 0;
}Làm thế nào để lặp select() để thăm dò ý kiến cho vô cùng tận dữ liệu
Làm thế nào để làm như vậy, nhưng không phải chỉ một lần, nhưng trong vòng lặp vô hạn mà phá vỡ sau khi gặp phải 'thoát' chuỗi (ví dụ) . Mọi cách tôi cố gắng - thất bại. Vì vậy, nếu không có dữ liệu nào được nhập sau chương trình 10 giây, chỉ cần in "10 giây đã qua - không có dữ liệu đầu vào" và sau đó bắt đầu chờ lại. Tương tự sau khi đầu vào - chỉ bắt đầu lại và hành xử giống nhau mỗi lần trong vòng lặp vô hạn.
Có chút tuyệt vọng, xin vui lòng - giúp đỡ.
Cảm ơn.
Đặt mọi thứ vào một vòng lặp 'while (! Strcmp (name," quit "))' hay gì đó? :-) –
"Ở đây, tham số đầu tiên là số lượng FD trong tập hợp" ** không **. Nó phải là số FD cao nhất cộng với một. Vui lòng kiểm tra lại trang người đàn ông. – Mat
Ví dụ ở dưới cùng của http://linux.die.net/man/2/select_tut là chính xác những gì bạn muốn. –