forked from lettergram/io_multiplexing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kqueue.c
96 lines (76 loc) · 1.78 KB
/
kqueue.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* Written by Austin Walters 5/13/2014
* For I/O Multiplexing example on austingwalters.com
*/
#include <sys/event.h>
#include <sys/time.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
/**
* Given the file descriptor this function,
* writes A, waits 2 second, writes "c,"
*/
void child_one_func(int fd){
write(fd, "A - 1", 5);
sleep(2);
write(fd, "C - 3", 5);
close(fd);
}
/**
* Given the file descriptor this function,
* Waits 1 second, writes "B", Waits 2 seconds,
* then writes "D"
*/
void child_two_func(int fd){
sleep(1);
write(fd, "B - 2", 5);
sleep(2);
write(fd, "D - 4", 5);
close(fd);
}
int main(){
int kq = kqueue();
/* Double-array of fds for the pipe() */
int **fds = malloc(2 * sizeof(int *));
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;
}