printf除非换行符在格式字符串中,为什么在调用后不刷新?这是POSIX的行为吗?我怎么可能printf每次都立即冲洗?
朋友给我发了个程序:
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
void chain(int n, int current_nr) {
printf("Running %d\n", current_nr);
pid_t pid = fork();
if (pid != 0) { //parent
return;
}
else { //child
if (current_nr == n - 2) {
return;
}
else {
chain(n, current_nr + 1);
}
}
}
int main(void) {
puts("Program started");
chain(5, 0);
wait(NULL);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果程序以./program形式执行,则输出为:
Program started
Running 0
Running 1
Running 2
Running 3
Run Code Online (Sandbox Code Playgroud)
但在执行./program> outputfile之后,输出文件内容为:
Program started
Running 0
Running …Run Code Online (Sandbox Code Playgroud)