How to check if stdin is still opened without blocking?

后端 未结 5 541
野性不改
野性不改 2021-01-02 00:57

I need my program written in pure C to stop execution when stdin is closed.

There is indefinite work done in program main cycle, and there is no way I can use blocki

5条回答
  •  -上瘾入骨i
    2021-01-02 01:27

    select() does exactly what you want: signal that an operation (read, in this case) on a file descriptor (file, socket, whatever) will not block.

    #include 
    #include 
    
    int is_ready(int fd) {
        fd_set fdset;
        struct timeval timeout;
        int ret;
        FD_ZERO(&fdset);
        FD_SET(fd, &fdset);
        timeout.tv_sec = 0;
        timeout.tv_usec = 1;
        //int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
         struct timeval *timeout);
        return select(fd+1, &fdset, NULL, NULL, &timeout) == 1 ? 1 : 0;
    }
    

    You can now check a file descriptor before use, for instance in order to empty the file descriptor:

    void empty_fd(int fd) {
        char buffer[1024];
        while (is_ready(fd)) {
            read(fd, buffer, sizeof(buffer));
        }
    }
    

    In your case, use fileno(stdin) to get the file descriptor of stdin:

    if (is_ready(fileno(stdin))) {
        /* read stuff from stdin will not block */
    }
    

提交回复
热议问题