天天看點

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) {

            e xit(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);

}

繼續閱讀