c/c++语言开发共享检查stdin是否为空

我搜索但没有得到这个问题的相关答案,我正在使用linux机器,我想检查标准输入流是否包含任何字符,而不从流中删除字符。

    您可能想尝试select()函数,并等待将数据输入到输入流中。

    描述:

    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 } } } 

    希望能帮助到你。

    cacho在正确的路径上,但是只有在处理多个文件描述符时才需要select ,并且stdin不是POSIX文件描述符( int ); 这是一个FILE * 。 如果你走这条路,你想要使用STDIN_FILENO

    这也不是一条非常干净的路线。 我更喜欢使用poll 。 通过将0指定为timeout ,poll将立即返回。

    如果在任何选定的文件描述符上都没有发生任何定义的事件,则poll()应至少等待超时毫秒,以便在任何选定的文件描述符上发生事件。 如果timeout的值为0,则poll()应立即返回。 如果timeout的值为-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. */ 

      以上就是c/c++开发分享检查stdin是否为空相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/545825.html

      (0)
      上一篇 2021年1月10日
      下一篇 2021年1月10日

      精彩推荐