【问题标题】:select() function don't allow printf() without "\n" in the endselect() 函数不允许 printf() 最后没有 "\n"
【发布时间】:2014-09-29 21:01:27
【问题描述】:

我在使用 select() 时遇到问题:它在我的程序中表现得很奇怪,我不明白为什么。

#include <stdio.h>
#include <netdb.h>

int main()
{
char msg[1024];

fd_set readfds;
int stdi=fileno(stdin);

FD_SET(stdi, &readfds);

for (;;) {
    printf("Input: ");
    select(stdi+1, &readfds, NULL, NULL, NULL);

    if (FD_ISSET(stdi, &readfds))
        {
        scanf("%s",msg);
        printf("OK\n");
        }
    }
}

您期望什么程序行为?大概和我一样(123是我输入的字符串):

Input: 123
OK

但真正的程序行为是这样的:

123
Input: OK

让我们将调用 printf("Input: ") 中的参数更改为 "Input: \n"。我们会得到的是

Input: 
123
OK

所以 select() 函数会冻结输出,直到下一个 printf() 以“\n”结尾。

我可以做些什么来获得我期望的行为?

【问题讨论】:

    标签: c sockets select io printf


    【解决方案1】:

    默认情况下,stdout 是行缓冲的,这意味着在遇到 '\n' 之前不会写入输出。因此,您需要在printf 之后使用fflush 来强制将缓冲的数据写入屏幕。

    另外,您可以使用常量STDIN_FILENO(始终为 0),而不是使用 fileno(stdin)

    【讨论】:

    • 伙计,你太棒了。非常感谢您提供如此快速而有用的帮助!来自俄罗斯的问候和祝福!
    【解决方案2】:

    fflush() 将所有缓冲数据刷新到关联的流中。这是为了提高系统的性能,所以 I/O 是批量发生的。

    【讨论】:

      猜你喜欢
      • 2018-06-25
      • 1970-01-01
      • 2020-08-15
      • 2019-10-30
      • 2021-09-02
      • 1970-01-01
      • 2014-07-28
      • 2012-04-27
      • 1970-01-01
      相关资源
      最近更新 更多