Skip to content

Instantly share code, notes, and snippets.

@celeron633
Created January 3, 2021 08:20
Show Gist options
  • Save celeron633/778519a97b4e7d9aeb1479e8278cb4b8 to your computer and use it in GitHub Desktop.
Save celeron633/778519a97b4e7d9aeb1479e8278cb4b8 to your computer and use it in GitHub Desktop.
simple epoll demo using pipe
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/epoll.h>
#include <unistd.h>
#define MAX_EPOLL_EVENTS 10
#define MAX_BUF_SIZE 10
#define MAX_READ_SIZE 5
int main(int argc, char* argv[]) {
int pipe_fd[2];
int pid;
int result;
char buf[MAX_BUF_SIZE];
int epoll_fd;
result = pipe(pipe_fd);
if (result < 0) {
perror("pipe failed!\n");
return -1;
}
pid = fork(); // fork
if (pid == 0) { // child read from pipe
close(pipe_fd[1]); // close the write end of pipe
char readBuf[10];
int result;
struct epoll_event ev;
struct epoll_event events[MAX_EPOLL_EVENTS];
result = epoll_fd = epoll_create(MAX_EPOLL_EVENTS);
if (result < 0) {
perror("epoll_create failed!\n");
return -1;
}
ev.events = EPOLLIN;
ev.data.fd = pipe_fd[0];
result = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, pipe_fd[0], &ev);
if (result < 0) {
perror("epoll_ctl failed!\n");
}
for (;;) {
int rNum = epoll_wait(epoll_fd, events, MAX_EPOLL_EVENTS, -1); // wait
printf("rNum is [%d]\n", rNum);
if (rNum < 0) {
perror("epoll_wait failed!\n");
}
for (int i = 0; i < rNum; i++) {
if (events[i].events == EPOLLIN) {
printf("fd [%d] is ready to read!\n", events[i].data.fd);
result = read(events[i].data.fd, (void*)readBuf, MAX_BUF_SIZE);
if (result < 0) {
perror("read failed!\n");
continue;
}
printf("read buf content from pipe: [%s]\n", readBuf);
}
}
}
} else if (pid > 0) { // parent write something to pipe
close(pipe_fd[0]);
int result;
char c = 'a';
for (;;) {
for (int i = 0; i < 5; i++) {
buf[i] = c;
}
buf[MAX_BUF_SIZE / 2] = '\n';
c++;
for (int i = 6; i < MAX_BUF_SIZE; i++) {
buf[i] = c;
}
buf[MAX_BUF_SIZE - 1] = '\n';
result = write(pipe_fd[1], (void*)buf, MAX_BUF_SIZE);
if(result < 0) {
perror("write failed!\n");
}
printf("write bytes to buf done! will sleep for [5] seconds!\n");
usleep(5 * 1000 * 1000);
}
} else if (pid < 0) {
perror("fork failed!\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment