tcflush与unbuffered I/O,buffered I/O




tcflush就是清除输入/输出数据的。但是我们会看到,采用不同的I/O函数确有不同的结果。
代码一:buffered I/O
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <termios.h> int main(void) { printf("hello word."); //可以看到输出,如果改为 printf("hello word./n"); 将看不到输出 if (tcflush(STDOUT_FILENO, TCIOFLUSH) == -1) { exit(1); } exit(0); }
代码二:unbuffered I/O
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <termios.h> #include <fcntl.h> int main(void) { char Myinfo[26]="hello word!"; //加不加‘/n’都无法看到输出 write(STDOUT_FILENO,Myinfo,26); if (tcflush(STDOUT_FILENO, TCIOFLUSH) == -1) { exit(1); } exit(0); }
分析其原因,其实就是因为printf是个buffered I/O函数,所以导致在调用tcflush的时候并没有真正的进入到终端输出文件中。我们再看下面的代码
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <termios.h> #include <fcntl.h> int main(void) { char Myinfo[26]="hello word!/n"; char Myinfo1[26]="jack"; printf("Hello"); write(STDOUT_FILENO,Myinfo1,26); //是必定无法看到的 if (tcflush(STDOUT_FILENO, TCIOFLUSH) == -1) { exit(1); } write(STDOUT_FILENO,Myinfo,26); exit(0); }

我们调用运行,可能会有多次不同的结果,有时候是:
hello word
Hello
也可能是:
Hello
hello word
那么是不是代码一中也可能是看不到结果的呢?答案应该是一定的,在特定的环境下,是会有这样的情况发生的。所以,如果要调用tcflush来达到目的,可以应该调用unbuffered I/O来避免不定因数的产生。当然也可以通过setvbuf(stdout, NULL, _IONBF, 0);来达到目的。如:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <termios.h> int main(void) { setvbuf(stdout, NULL, _IONBF, 0); printf("hello word."); //将无法看到输出 if (tcflush(STDOUT_FILENO, TCIOFLUSH) == -1) { exit(1); } exit(0); }

你可能感兴趣的:(null,终端)