6 #include <sys/resource.h>
13 static int n_children
= 3;
14 static int n_active_children
;
15 static int n_iters
= 10000;
17 static int write_fds
[1024];
18 static struct pollfd poll_fds
[1024];
25 fprintf (stderr
, "Cannot create pipe %s\n", strerror (errno
));
31 read_all (int fd
, char *buf
, int len
)
36 while (bytes_read
< len
)
38 count
= read (fd
, buf
+ bytes_read
, len
- bytes_read
);
54 write_all (int fd
, char *buf
, int len
)
56 int bytes_written
= 0;
59 while (bytes_written
< len
)
61 count
= write (fd
, buf
+ bytes_written
, len
- bytes_written
);
68 bytes_written
+= count
;
75 run_child (int in_fd
, int out_fd
)
80 for (i
= 0; i
< n_iters
; i
++)
82 write_all (out_fd
, (char *)&val
, sizeof (val
));
83 read_all (in_fd
, (char *)&val
, sizeof (val
));
87 write_all (out_fd
, (char *)&val
, sizeof (val
));
93 input_callback (int source
, int dest
)
97 if (!read_all (source
, (char *)&val
, sizeof(val
)))
99 fprintf (stderr
,"Unexpected EOF\n");
105 write_all (dest
, (char *)&val
, sizeof(val
));
119 create_child (int pos
)
130 if (pid
> 0) /* Parent */
135 write_fds
[pos
] = in_fds
[1];
136 poll_fds
[pos
].fd
= out_fds
[0];
137 poll_fds
[pos
].events
= POLLIN
;
139 else if (pid
== 0) /* Child */
146 run_child (in_fds
[0], out_fds
[1]);
150 fprintf (stderr
,"Cannot fork: %s\n", strerror (errno
));
156 difftimeval (struct timeval
*old
, struct timeval
*new)
159 (new->tv_sec
- old
->tv_sec
) * 1000. + (new->tv_usec
- old
->tv_usec
) / 1000;
163 main (int argc
, char **argv
)
166 struct rusage old_usage
;
167 struct rusage new_usage
;
170 n_children
= atoi(argv
[1]);
173 n_iters
= atoi(argv
[2]);
175 printf ("Children: %d Iters: %d\n", n_children
, n_iters
);
177 n_active_children
= n_children
;
178 for (i
= 0; i
< n_children
; i
++)
181 getrusage (RUSAGE_SELF
, &old_usage
);
183 while (n_active_children
> 0)
185 int old_n_active_children
= n_active_children
;
187 poll (poll_fds
, n_active_children
, -1);
189 for (i
=0; i
<n_active_children
; i
++)
191 if (poll_fds
[i
].events
& (POLLIN
| POLLHUP
))
193 if (!input_callback (poll_fds
[i
].fd
, write_fds
[i
]))
198 if (old_n_active_children
> n_active_children
)
201 for (i
=0; i
<old_n_active_children
; i
++)
203 if (write_fds
[i
] != -1)
207 poll_fds
[j
] = poll_fds
[i
];
208 write_fds
[j
] = write_fds
[i
];
216 getrusage (RUSAGE_SELF
, &new_usage
);
218 printf ("Elapsed user: %g\n",
219 difftimeval (&old_usage
.ru_utime
, &new_usage
.ru_utime
));
220 printf ("Elapsed system: %g\n",
221 difftimeval (&old_usage
.ru_stime
, &new_usage
.ru_stime
));
222 printf ("Elapsed total: %g\n",
223 difftimeval (&old_usage
.ru_utime
, &new_usage
.ru_utime
) +
224 difftimeval (&old_usage
.ru_stime
, &new_usage
.ru_stime
));
225 printf ("total / iteration: %g\n",
226 (difftimeval (&old_usage
.ru_utime
, &new_usage
.ru_utime
) +
227 difftimeval (&old_usage
.ru_stime
, &new_usage
.ru_stime
)) /
228 (n_iters
* n_children
));