码迷,mamicode.com
首页 > 其他好文 > 详细

非阻塞的c/s,epoll服务器模型

时间:2018-05-25 21:19:33      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:class   read   errno   out   \n   file   stdout   cpp   eof   

epoll

#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <errno.h>
#include <unistd.h>

#define MAXLINE 10

int main(int argc, char *argv[])
{
    int efd, i;
    int pfd[2];
    pid_t pid;
    char buf[MAXLINE], ch = ‘a‘;

    pipe(pfd);
    pid = fork();

    if (pid == 0) {
        close(pfd[0]);
        while (1) {
            for (i = 0; i < MAXLINE/2; i++)
                buf[i] = ch;
            buf[i-1] = ‘\n‘;
            ch++;
            for (; i < MAXLINE; i++)
                buf[i] = ch;
            buf[i-1] = ‘\n‘;
            ch++;
            write(pfd[1], buf, sizeof(buf));
            sleep(2);
        }
        close(pfd[1]);
    }
    else if (pid > 0) {
        struct epoll_event event;
        struct epoll_event resevent[10];
        int res, len;
        close(pfd[1]);
        efd = epoll_create(10);
        /* ET 边沿触发 ,默认是水平触发 */
        event.events = EPOLLIN | EPOLLET;
        /* event.events = EPOLLIN; */
        event.data.fd = pfd[0];
        epoll_ctl(efd, EPOLL_CTL_ADD, pfd[0], &event);
        while (1) {
            res = epoll_wait(efd, resevent, 10, -1);
            printf("res %d\n", res);
            if (resevent[0].data.fd == pfd[0]) {
                len = read(pfd[0], buf, MAXLINE/2);
                write(STDOUT_FILENO, buf, len);
            }
        }
        close(pfd[0]);
        close(efd);
    }
    else {
        perror("fork");
        exit(-1);
    }

    return 0;
}

  

非阻塞的c/s,epoll服务器模型

标签:class   read   errno   out   \n   file   stdout   cpp   eof   

原文地址:https://www.cnblogs.com/yjds/p/9090316.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!