szaydel
8/10/2019 - 4:06 AM

fifos with epoll

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>           /* Definition of AT_* constants */
#include <errno.h>
#include <sys/epoll.h>

int main(void) {
    int fds[2];

    if (mkfifo("./fifo1", 0644) < 0) {
        perror("mkfifo()");
    };

    if (mkfifo("./fifo2", 0644) < 0) {
        perror("mkfifo()");
    };

    if ((fds[0] = open("./fifo1", O_RDONLY|O_NONBLOCK, 0644)) < 0)
        perror("open()");

    if ((fds[1] = open("./fifo2", O_RDONLY|O_NONBLOCK, 0644)) < 0)
        perror("open()");

    int epfd;
    struct epoll_event ev[2] = {0};
    struct epoll_event evlist[2];

    epfd = epoll_create(2);
    if (epfd == -1) {
        perror("epoll_create");
        exit(EXIT_FAILURE);
    }
    ev[0].data.fd = fds[0];
    ev[0].events = EPOLLIN;
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, fds[0], &ev[0]) == -1) {
        perror("epoll_ctl");
        exit(EXIT_FAILURE);
    }

    ev[1].data.fd = fds[1];
    ev[1].events = EPOLLIN;
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, fds[1], &ev[1]) == -1) {
        perror("epoll_ctl");
        exit(EXIT_FAILURE);
    }

    while (1) {
        int ready = epoll_wait(epfd, evlist, 2, -1);
        if (ready == -1) {
            if (errno == EINTR)
                continue;
            else {
                perror("epoll_wait()");
                exit(EXIT_FAILURE);
            }
        }
        printf("ready: %d\n", ready);
    }
    // char buf[4096] = {0};
    // ssize_t n;
    // ssize_t result;
    // size_t remains;
    // for (;;) {
    //     char *p = buf;
    //     n = 0;
    //     remains = 4096;
    //     while (remains > 0) {
    //         if ((result = read(fds[0], p, remains)) == -1) {
    //             if (errno == EAGAIN || errno == ETIMEDOUT) {
    //                 sleep(1);
    //                 continue;
    //             } else {
    //                 perror("read()");
    //                 exit(EXIT_FAILURE);
    //             }
    //         }
    //         n += result;
    //         remains -= result;
    //         printf("%s", p);
    //         p += n;
    //     }
    // }
}