c_cpp 非块阅读

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 非块阅读相关的知识,希望对你有一定的参考价值。

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/uio.h>

int main(void)
{
    char buf[80];
    ssize_t size;
    int fd = fileno(stdin);

    // Non-blocking I/O; if no data is available to a read call, or if a write operation
    // would block, the read or write call returns -1 with the error EAGAIN.
    int flags = fcntl(fd, F_GETFL, 0);
    fcntl(fd, F_SETFL, flags | O_NONBLOCK);

    // manual poll
    while (size = read(fd, buf, sizeof(buf))) {
        printf("Current size %d\n", size);
        if (size == -1) {
            if (errno != EAGAIN) {
                perror("read()");
                exit(EXIT_FAILURE);
            }
            // data not ready, wait and check again
            perror(NULL);
            sleep(3);
        }
    }

    printf("%s", buf);

    return EXIT_SUCCESS;
}

以上是关于c_cpp 非块阅读的主要内容,如果未能解决你的问题,请参考以下文章