select()函数不允许printf()没有" \ n"到底 [英] select() function don't allow printf() without "\n" in the end
问题描述
我在使用select()时遇到问题:它在我的程序中表现得很奇怪,我无法理解为什么。
I have a problem using select(): it acts strange in my program and I can't understand why.
#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是我输入的字符串):
What program behavior do you expect? Probably same as me (123 is a string I enter):
Input: 123
OK
但真正的程序行为如下所示:
But the real program behavior looks like this:
123
Input: OK
让我们改变调用printf中的争论(输入:)到输入:\ n。我们得到的是
Let's change arguement in call printf("Input: ") to "Input: \n". What we'll get is
Input:
123
OK
所以select()函数是冻结输出,直到下一个printf()以\ n结尾。
So select() function is freezing output untill next printf() ending with "\n".
我能做些什么来获得我期望的行为?
What can I do to get the behavior I expected?
推荐答案
默认情况下, stdout
是行缓冲的,这意味着在遇到'\ n'
之前不会写入输出。因此,您需要在 printf
之后使用 fflush
来强制将缓冲的数据写入屏幕。
By default, stdout
is line-buffered, meaning output is not written until a '\n'
is encountered. So, you need to use fflush
after the printf
to force the buffered data to be written to the screen.
此外,您可以使用常量 STDIN_FILENO <而不是
fileno(stdin)
。 / code>(总是0)。
Also, instead of doing fileno(stdin)
, you can just use the constant STDIN_FILENO
(which is always 0).
这篇关于select()函数不允许printf()没有" \ n"到底的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!