2013-04-26 265 views
7

我搜索了但沒有得到相關的答案,我正在linux機器上工作,我想檢查標準輸入流是否包含任何字符,而不從流中移除字符。檢查標準輸入是否爲空

+1

C++ or C?你的問題標有兩個。 – 2013-04-26 04:52:24

+3

我不確定你的問題有明確的含義。想象一下* stdin *是一個管道(從一個需要年齡的命令中將其第一個字符吐出* stdout *)。你可以用'STDIN_FILENO'(即0)作爲文件描述符來調用[poll(2)](http://man7.org/linux/man-pages/man2/poll.2.html)。然後檢查* stdin *是否可讀...(即[read(2)](http://man7.org/linux/man-pages/man2/read.2.html)不會被阻止)。 – 2013-04-26 04:52:43

回答

6

您可能想嘗試select()函數,並等待將數據輸入到輸入流中。

說明:

選擇()和PSELECT()允許一個程序來監視多個文件 描述,等到一個或多個文件描述符成爲 「準備就緒」的一些類的I/O操作(例如,可能的輸入)。如果可以在沒有阻塞的情況下執行對應的I/O操作(例如,讀取(2)),則文件 描述符被認爲是準備好的。

在你的情況,文件描述符將stdin

void yourFunction(){ 
    fd_set fds; 
    struct timeval timeout; 
    int selectRetVal; 

    /* Set time limit you want to WAIT for the fdescriptor to have data, 
     or not(you can set it to ZERO if you want) */ 
    timeout.tv_sec = 0; 
    timeout.tv_usec = 1; 

    /* Create a descriptor set containing our remote socket 
     (the one that connects with the remote troll at the client side). */ 
    FD_ZERO(&fds); 
    FD_SET(stdin, &fds); 

    selectRetVal = select(sizeof(fds)*8, &fds, NULL, NULL, &timeout); 

    if (selectRetVal == -1) { 
     /* error occurred in select(), */ 
     printf("select failed()\n"); 
    } else if (selectRetVal == 0) { 
     printf("Timeout occurred!!! No data to fetch().\n"); 
     //do some other stuff 
    } else { 
     /* The descriptor has data, fetch it. */ 
     if (FD_ISSET(stdin, &fds)) { 
      //do whatever you want with the data 
     } 
    } 
} 

希望它能幫助。

+3

感謝您的即時rply,但是,我不想等待輸入流有數據, 它只是,如果流有數據,我需要做一些處理,如果它沒有數據,做一些其他處理。代碼不應該等待輸入, – 51k 2013-04-26 05:11:30

+0

我仍然認爲這可以幫助@ 51k,讓我舉個例子。 – 2013-04-26 05:18:10

4

卡丘是在正確的道路上,但是select只有當你處理一個以上的文件描述符必要的,stdin不是POSIX文件描述符(int);這是一個FILE *。如果你走這條路線,你會想要使用STDIN_FILENO

這也不是一個非常乾淨的路線。我寧願使用poll。通過指定0作爲timeout,輪詢將立即返回。

如果沒有定義的事件都發生在任何選定的文件 描述符,則poll()應至少等待超時毫秒爲任何所選擇的文件描述符發生的 事件。 如果超時值 爲0,poll()應立即返回。如果 的值超時爲-1,則poll()應阻塞,直到發生請求的事件或 ,直到呼叫中斷。

struct pollfd stdin_poll = { .fd = STDIN_FILENO 
          , .events = POLLIN | POLLRDBAND | POLLRDNORM | POLLPRI }; 
if (poll(&stdin_poll, 1, 0) == 1) { 
    /* Data waiting on stdin. Process it. */ 
} 
/* Do other processing. */