select() 函数不允许 printf() 最后没有 "\n"

Iva*_*off 0 c sockets io select printf

我在使用 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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Input: 123
OK
Run Code Online (Sandbox Code Playgroud)

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

123
Input: OK
Run Code Online (Sandbox Code Playgroud)

让我们将 call printf("Input: ") 中的争论改为 "Input: \n"。我们将得到的是

Input: 
123
OK
Run Code Online (Sandbox Code Playgroud)

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

我该怎么做才能获得预期的行为?

Dre*_*wen 5

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

此外,fileno(stdin)您可以只使用常量STDIN_FILENO(始终为 0),而不是执行。