c - 如何在 C 中超时后调用选择?

标签 c

我使用 select 进行同步 I/O 多路复用。它将检查任何数据 1 秒。1 秒后如果没有数据,它将显示输出 (puts("Waited for 1 sec no data");) 然后它会再次检查数据。但这只在第一次工作然后它进入无限循环。 是否有任何替代解决方案。

//..............................
//.............................
//Creating listener socket and other sort of things
struct timeval tv;
        tv.tv_sec=1;
        tv.tv_usec=0;

    while(1)
    {
    FD_ZERO(master);


    FD_SET(listener,master);
    fdmax = listener;
    int retval=select(fdmax+1,master, NULL, NULL,&tv);
    printf("retval is %d\n",retval);

            if(retval == -1)
            {
                    perror("Server-select() error");
            }else if(retval)
            {
                    puts("Data available");
                    //If there is no data do some work and checkagain.

            }else
            {
                    puts("Waited for 1 sec no data"); 
                    //If there is no data do some work and checkagain.

            }
      }

最佳答案

来自 man select :

On Linux, select() modifies timeout to reflect the amount of time not slept; most other implementations do not do this. (POSIX.1-2001 permits either behavior.) This causes problems both when Linux code which reads timeout is ported to other operating systems, and when code is ported to Linux that reuses a struct timeval for multiple select()s in a loop without reinitializing it. Consider timeout to be undefined after select() returns.

所以像 master 一样,您必须在每次 select 调用之前设置 tv

在我的代码中,我经常有这样的东西:

FD_ZERO(master);
FD_SET(listener,master);
fdmax = listener;

while (1)
{
    struct timeval tv = {1, 0};

    int retval=select(fdmax+1,master, NULL, NULL,&tv);
    printf("retval is %d\n",retval);

    if(retval == -1) {
        perror("Server-select() error");
        break; //  <-- notice the break here
    } else if(retval) {
        puts("Data available");
    } else {
        puts("Waited for 1 sec no data"); 
    }
}

关于c - 如何在 C 中超时后调用选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36786460/

相关文章:

c - 为什么允许命名嵌套结构?

c - pthread_exit() 和 exit() 之间的区别?

c++ - 这段代码不是线程安全的,不是吗?

c - 我必须包含哪个头文件才能在内核源文件中获取 printk()?

c - 正确构建 if 语句

c++ - 使用 c/c++ 宏禁用多行语句

c - 需要帮助读取 C 中的文件

c - 从内存中读取数据

c - 我如何知道两个exe是否有不同的代码?

c++ - pcm_plug.c :67: snd_pcm_plug_close: Assertion `plug->gen.slave == plug->req_slave' failed