c - unix select() 调用 : how to combine fd_sets?

标签 c unix network-programming

我正在用 C 为 linux 编写一个应用程序,它使用 2 个独立的第三方库。这两个库都是异步的并使用 select()。他们还提供了一个 API,可以返回他们等待的文件描述符。我的意图是将它们传递到我自己的 select() 中,然后在设置它们自己的 fd 值时将控制返回给任何库。

我想我已经写了大部分,但我在 select() 参数方面遇到了麻烦:两个库都没有提供单独的文件描述符,而是指向它们的读写 fd_sets 的指针。我需要将从这些库返回的 fd_sets 组合成一个 fd_set 用于读取,一个 fd_set 用于写入等。

关于如何将 2 个 fd_set 组合成一个结果 fd_set 有什么建议吗?

附录 抱歉!我应该更清楚..这些库只返回 fd_sets...我不知道每组中的 FD 数量,所以我可以做一个 for 循环并单独设置每个 FD..有没有一种简单的方法来确定这只是一个 fd_set?

最佳答案

不依赖fd_set实现的C代码:

void Fdset_Add(fd_set *Out, fd_set const *In, int InNfds)
{
    for(i = 0; i < InNfds; i++)
    {
        if(i < InNfds && FD_ISSET(i, In))
            FD_SET(i, Out);
    }
}

int Fdset_Merge(fd_set *Out, fd_set const *In1, int NFds1, fd_set const *In2, int NFds2)
{
    FD_ZERO(Out);
    Fdset_Add(Out, In1, Nfds1);
    Fdset_Add(Out, In2, Nfds2);
    return Nfds1 > Nfds2 ? Nfds1 : Nfds2;
}

int Fdset_Filter(fd_set const *Result, int ResultNfds, fd_set *ToFilter, int NfdsToFilter)
{
    int i;
    int Retval;

    Retval = 0;
    for(i = 0; i < ResultNfds; i++)
    {
        if(i < NfdsToFilter && FD_ISSET(i, ToFilter))
        {
            if(! FD_ISSET(i, Result))
                FD_CLR(i, ToFilter);
            else
                Retval++;
        }
    }
    return Retval;
}

void Fdset_Split(fd_set const *Result, int ResultNfds, fd_set *In1, int Nfds1, int *Count1, fd_set *In2, int Nfds2, int *Count2)
{
     *Count1 = Fdset_Filter(Result, ResultNfds, In1, Nfds1);
     *Count2 = Fdset_Filter(Result, ResultNfds, In1, Nfds2);
}

关于c - unix select() 调用 : how to combine fd_sets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3195515/

相关文章:

bash - unix中时间命令的开销

python - 为什么这段代码在不同的发行版/Unix 上表现不同?

unix - 使用 grep 进行多种搜索模式

c - 在 C 程序中使用 printf() 两次

c - 如何在我的系统 (Mac OS) 上找到 C getchar() 的实现?

c - 递归搜索未排序数组上的元素

ssl - Asio 流式传输 - 使用 SSL/TLS 加密的速度较慢

c - 是否可以使用STM32生成CAN总线错误?

c# - 一台服务器可以处理多少个不同端口上的tcp连接?

linux - 为什么recvfrom()会报告数据包大小?