Skip to content

Instantly share code, notes, and snippets.

@lettergram lettergram/kqueue
Created Mar 19, 2015

Embed
What would you like to do?
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;
}
@jubajube

This comment has been minimized.

Copy link

jubajube commented May 26, 2016

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.