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

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

#include  #include  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()函数是冻结输出,直到下一个以“\ n”结尾的printf()。

我能做些什么才能得到我期望的行为?

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

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

fflush()将所有缓冲的数据刷新到关联的流上。 它是为了增强系统的性能,因此I / O大量发生。