c - 在 C 中将标准输入与 select() 结合使用

标签 c linux sockets file-descriptor

我有以下程序:

 #include <stdio.h>
 #define STDIN 0

 int main()
 {

    fd_set fds;
    int maxfd;
    // sd is a UDP socket

    maxfd = (sd > STDIN)?sd:STDIN;

    while(1){

        FD_ZERO(&fds);
        FD_SET(sd, &fds); 
        FD_SET(STDIN, &fds); 

        select(maxfd+1, &fds, NULL, NULL, NULL); 

        if (FD_ISSET(STDIN, &fds)){
              printf("\nUser input - stdin");
        }
        if (FD_ISSET(sd, &fds)){
              // socket code
        }
     }
 }

我面临的问题是,一旦在 STDIN 上检测到输入,消息“用户输入 - stdin”就会继续打印...为什么它不只打印一次并在下一个 while 循环检查哪个描述符有输入?

谢谢。

最佳答案

select 函数仅在有可用输入时通知您。如果您实际上没有消耗它,select 将继续直接下降。

关于c - 在 C 中将标准输入与 select() 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10219340/

相关文章:

.net - 用 mkbundle2 打包后,目标机器提示 libmono.so。为什么?

c++ - 无法通过无线网络上的 UDP 广播快速传输

python - python套接字程序: Cannot assign requested address

c - 具有平面 .obj 目录的 manu 源目录的非递归 makefile

c - 释放C中的三重指针

linux - Wget 能否返回 true 或 false(0 或 1)

c - 使用套接字时如何获得下载速度?

c++ - 从森林中构建一棵 n 叉树

c - 为什么会发生这种情况的想法? printf 让我的代码工作

Android Studio 错误 13=权限在 linux 中被拒绝