如何循环 select() 来无限轮询数据

问题描述 投票:0回答:2
#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;

}

如何做同样的事情,但不仅仅是一次,而是在无限循环中,在遇到“quit”字符串(例如)后中断。我尝试过的每一种方法都失败了。 因此,如果 10 秒后没有输入数据,程序只会打印“10 秒结束 - 没有数据输入”,然后再次开始等待。输入后相同 - 只是再次开始并在无限循环中每次都表现相同。

c loops pool posix-select
2个回答
5
投票

我真的没有看到这里的问题。基本上只需将您想要的所有内容放入循环中,然后让它运行即可。你尝试过这个吗?

int main ()
{
   /* Declarations and stuff */
   /* ... */

   /* The loop */
   int break_condition = 0;
   while (!break_condition)
   {
       /* Selection */
       FD_ZERO(&input_set );   /* Empty the FD Set */
       FD_SET(0, &input_set);  /* Listen to the input descriptor */
       ready_for_reading = select(1, &input_set, NULL, NULL, &timeout);

       /* Selection handling */
       if (ready_for_reading)
       {
          /* Do something clever with the input */
       }
       else
       {
          /* Handle the error */
       }

       /* Test the breaking condition */
       break_condition = some_calculation();
   }
   return 0;
}

请注意,您必须不断重置循环内的选择,以便它在下一次迭代中再次响应。


0
投票

可以通过将 timeout 设置为 NULL 来让 select() 函数无限期地阻塞。请参阅 select(2) 手册页:

timeoutselect() 返回之前经过的时间量的上限。如果 timeval 结构的两个字段都为零,则 select() 立即返回。 (这对于轮询很有用。)如果 timeout 为 NULL(无超时),select() 可以无限期阻塞。

所以你想要的是:

...
ready_for_reading = select(1, &input_set, NULL, NULL, NULL);
...
© www.soinside.com 2019 - 2024. All rights reserved.