2013-04-26 191 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. */