1
#undef G_DISABLE_ASSERT
9
#include <sys/resource.h>
16
static int n_children = 3;
17
static int n_active_children;
18
static int n_iters = 10000;
20
static int write_fds[1024];
21
static struct pollfd poll_fds[1024];
28
fprintf (stderr, "Cannot create pipe %s\n", strerror (errno));
34
read_all (int fd, char *buf, int len)
36
size_t bytes_read = 0;
39
while (bytes_read < len)
41
count = read (fd, buf + bytes_read, len - bytes_read);
57
write_all (int fd, char *buf, int len)
59
size_t bytes_written = 0;
62
while (bytes_written < len)
64
count = write (fd, buf + bytes_written, len - bytes_written);
71
bytes_written += count;
78
run_child (int in_fd, int out_fd)
83
for (i = 0; i < n_iters; i++)
85
write_all (out_fd, (char *)&val, sizeof (val));
86
read_all (in_fd, (char *)&val, sizeof (val));
90
write_all (out_fd, (char *)&val, sizeof (val));
96
input_callback (int source, int dest)
100
if (!read_all (source, (char *)&val, sizeof(val)))
102
fprintf (stderr,"Unexpected EOF\n");
108
write_all (dest, (char *)&val, sizeof(val));
122
create_child (int pos)
133
if (pid > 0) /* Parent */
138
write_fds[pos] = in_fds[1];
139
poll_fds[pos].fd = out_fds[0];
140
poll_fds[pos].events = POLLIN;
142
else if (pid == 0) /* Child */
149
run_child (in_fds[0], out_fds[1]);
153
fprintf (stderr,"Cannot fork: %s\n", strerror (errno));
159
difftimeval (struct timeval *old, struct timeval *new)
162
(new->tv_sec - old->tv_sec) * 1000. + (new->tv_usec - old->tv_usec) / 1000;
166
main (int argc, char **argv)
169
struct rusage old_usage;
170
struct rusage new_usage;
173
n_children = atoi(argv[1]);
176
n_iters = atoi(argv[2]);
178
printf ("Children: %d Iters: %d\n", n_children, n_iters);
180
n_active_children = n_children;
181
for (i = 0; i < n_children; i++)
184
getrusage (RUSAGE_SELF, &old_usage);
186
while (n_active_children > 0)
188
int old_n_active_children = n_active_children;
190
poll (poll_fds, n_active_children, -1);
192
for (i=0; i<n_active_children; i++)
194
if (poll_fds[i].events & (POLLIN | POLLHUP))
196
if (!input_callback (poll_fds[i].fd, write_fds[i]))
201
if (old_n_active_children > n_active_children)
204
for (i=0; i<old_n_active_children; i++)
206
if (write_fds[i] != -1)
210
poll_fds[j] = poll_fds[i];
211
write_fds[j] = write_fds[i];
219
getrusage (RUSAGE_SELF, &new_usage);
221
printf ("Elapsed user: %g\n",
222
difftimeval (&old_usage.ru_utime, &new_usage.ru_utime));
223
printf ("Elapsed system: %g\n",
224
difftimeval (&old_usage.ru_stime, &new_usage.ru_stime));
225
printf ("Elapsed total: %g\n",
226
difftimeval (&old_usage.ru_utime, &new_usage.ru_utime) +
227
difftimeval (&old_usage.ru_stime, &new_usage.ru_stime));
228
printf ("total / iteration: %g\n",
229
(difftimeval (&old_usage.ru_utime, &new_usage.ru_utime) +
230
difftimeval (&old_usage.ru_stime, &new_usage.ru_stime)) /
231
(n_iters * n_children));