Created
March 19, 2015 00:26
-
-
Save lettergram/9b0e2e20ceea019ed32b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int main(){ | |
/** | |
* Create the epoll() | |
* | |
* From man pages | |
* Since Linux 2.6.8, the | |
* size argument is ignored, | |
* but must be greater than zero; | |
*/ | |
int epoll_fd = epoll_create(1); | |
/* Double-array of fds for the pipe() */ | |
int **fds = malloc(2 * sizeof(int *)); | |
/* Each process needs its own epoll struct */ | |
struct epoll_event event[2]; | |
/* Create two processs */ | |
int i; | |
for (i = 0; i < 2; i++){ | |
/* Create a pipe */ | |
fds[i] = malloc(2 * sizeof(int)); | |
pipe(fds[i]); | |
int read_fd = fds[i][0]; | |
int write_fd = fds[i][1]; | |
/* Generates a new process */ | |
pid_t pid = fork(); | |
/* child */ | |
if (pid == 0){ | |
close(read_fd); | |
if (i == 0) { child_one_func(write_fd); } | |
else if (i == 1) { child_two_func(write_fd); } | |
/* Closes child */ | |
exit(0); | |
}else{ | |
close(write_fd); | |
} | |
/* Setup the epoll_event for this process */ | |
event[i].events = EPOLLIN; | |
/* Parent process listening to read file descriptor */ | |
event[i].data.fd = read_fd; | |
/* Add read_fd to event[i] or (Read) event on epoll_fds -- event[i] */ | |
epoll_ctl( epoll_fd, EPOLL_CTL_ADD, read_fd, &event[i]); | |
} | |
/** | |
* Read data via epoll_wait() | |
* It prints out the data as it comes in. | |
*/ | |
while(1){ | |
struct epoll_event ev; | |
epoll_wait(epoll_fd, &ev, 1, -1); | |
char str[10]; | |
ssize_t bytes = read(ev.data.fd, &str, 10); | |
/* If the ev.data.fd has bytes added print, else wait */ | |
if(bytes > 0) | |
printf("Read: %s\n", str); | |
else | |
epoll_ctl(epoll_fd, EPOLL_CTL_DEL, ev.data.fd, NULL); | |
if(strcmp(str, "D - 4") == 0) | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment