Check if stdin is empty

假装没事ソ 提交于 2020-01-14 07:43:18

问题


I searched but did not get a relevant answer to this question, i am working on a linux machine, i wanted to check if the standard input stream contains any character, without removing the characters from the stream.


回答1:


You might want to try select() function, and wait for having data into the input stream.

Description:

select() and pselect() allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform the corresponding I/O operation (e.g., read(2)) without blocking.

In your case, the file descriptor will be 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
        }
    }
}

Hope it helps.




回答2:


cacho was on the right path, however select is only necessary if you're dealing with more than one file descriptor, and stdin is not a POSIX file descriptor (int); It's a FILE *. You'd want to use STDIN_FILENO, if you go that route.

It's not a very clean route to take, either. I'd prefer to use poll. By specifying 0 as the timeout, poll will return immediately.

If none of the defined events have occurred on any selected file descriptor, poll() shall wait at least timeout milliseconds for an event to occur on any of the selected file descriptors. If the value of timeout is 0, poll() shall return immediately. If the value of timeout is -1, poll() shall block until a requested event occurs or until the call is interrupted.

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. */


来源:https://stackoverflow.com/questions/16228990/check-if-stdin-is-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!