![](/img/trans.png)
[英]CGI program timeout when reading/writing, respectively, from/to stdin/stdout
[英]Does reading from stdin flush stdout?
当连接到终端时,stdout是行缓冲的,但我记得在某处读取(至少从stdin)将自动刷新stdout。 我使用的所有C实现都已经完成了,但我现在无法在标准中找到它。
它确实有意义,它是这样的,否则代码如下:
printf("Type some input: ");
fgets(line, sizeof line, stdin);
需要额外的fflush(stdout);
那么stdout肯定会在这里刷新吗?
编辑:
正如几个回复所说,标准中似乎无法保证我的示例中的stdout输出将在从stdin读取之前出现,但另一方面,这个意图在(我的免费草稿副本)中说明了标准:
交互设备的输入和输出动态应按照7.19.3的规定进行。 这些要求的目的是尽快出现无缓冲或行缓冲输出,以确保在程序等待输入之前实际出现提示消息。
(ISO / IEC 9899:TC2委员会草案 - 2005年5月6日,第14页)。
所以似乎没有保证,但无论如何它可能适用于大多数实现。 (著名遗言...)
不,不是的。
要回答你的问题, 你需要额外的fflush(stdout);
在printf()
调用之后,确保在程序尝试读取输入之前出现提示。 从stdin
读取不是fflush(stdout);
为了你。
不,你需要fflush(stdout); 许多实现将在它们将输出发送到终端的每个换行符时刷新。
编号stdin / stdout是缓冲的。 您需要明确fflush(stdout)
,以便将视频内存/ unix终端内存中的缓冲数据推送到视图设备(如终端)。 可以通过调用setvbuf
来设置数据的缓冲。
编辑:感谢Jonathan,回答这个问题,从stdin读取不会刷新stdout。 我可能通过指定演示如何使用setvbuf
的代码来解决这个问题。
#include int main(void) { FILE *input, *output; char bufr[512]; input = fopen("file.in", "r+b"); output = fopen("file.out", "w"); /* set up input stream for minimal disk access, using our own character buffer */ if (setvbuf(input, bufr, _IOFBF, 512) != 0) printf("failed to set up buffer for input file\n"); else printf("buffer set up for input file\n"); /* set up output stream for line buffering using space that will be obtained through an indirect call to malloc */ if (setvbuf(output, NULL, _IOLBF, 132) != 0) printf("failed to set up buffer for output file\n"); else printf("buffer set up for output file\n"); /* perform file I/O here */ /* close files */ fclose(input); fclose(output); return 0; }
希望这会有所帮助,最好的问候,汤姆。
不,这不是标准的一部分。 您可能已经使用了一个库实现,其中您描述的行为确实发生了,但这是一个您不应该依赖的非标准扩展。
注意:当在stdin上读取或在stdout块上写入时,在处理std流时注意进程间死锁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.