Created
March 19, 2015 00:27
-
-
Save lettergram/e4d6f6fe6e5d32d1c00e 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 kqueue() */ | |
int kq = kqueue(); | |
/* Double-array of fds for the pipe() */ | |
int **fds = malloc(2 * sizeof(int *)); | |
/* Create an array for the changelist and eventlist kevent structs */ | |
struct kevent *evlist = malloc(sizeof(struct kevent)); | |
struct kevent *chlist = malloc(sizeof(struct kevent) * 2); | |
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); | |
} | |
/* Set listener to read */ | |
EV_SET(&chlist[i], read_fd, EVFILT_READ, EV_ADD, 0, 0, NULL); | |
} | |
char str[10]; | |
while(1){ | |
/* Grab any events */ | |
kevent(kq, chlist, 1, evlist, 1, NULL); | |
for(i = 0; i < 2; i++){ | |
ssize_t bytes = read(chlist[i].ident, &str, 10); | |
if(bytes > 0) | |
printf("Read: %s\n", str); | |
if(strcmp(str, "D - 4") == 0) | |
return 0; | |
} | |
} | |
free(chlist); | |
free(evlist); | |
close(kq); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this example! I think I found a bug however. Line 48, the third argument to kevent() should probably be 2, not 1, since you have two elements in the changelist. Otherwise, if child two writes to its pipe but child one doesn't, you'll never know.