11 #define rprintf fprintf
13 #define exit_cleanup(x) exit(1)
15 #define STDIN_FILENO 0
16 #define STDOUT_FILENO 1
18 #define TOTAL_SIZE (10*1024*1024)
20 static int write_loop(int fd, char *buf, int size)
25 int n = write(fd, buf, size);
34 int piped_child(char *command,int *f_in,int *f_out)
38 int from_child_pipe[2];
40 if (pipe(to_child_pipe) < 0 ||
41 pipe(from_child_pipe) < 0) {
42 rprintf(FERROR,"pipe: %s\n",strerror(errno));
43 exit_cleanup(RERR_IPC);
49 rprintf(FERROR,"fork: %s\n",strerror(errno));
50 exit_cleanup(RERR_IPC);
55 if (dup2(to_child_pipe[0], STDIN_FILENO) < 0 ||
56 close(to_child_pipe[1]) < 0 ||
57 close(from_child_pipe[0]) < 0 ||
58 dup2(from_child_pipe[1], STDOUT_FILENO) < 0) {
59 rprintf(FERROR,"Failed to dup/close : %s\n",strerror(errno));
60 exit_cleanup(RERR_IPC);
62 if (to_child_pipe[0] != STDIN_FILENO) close(to_child_pipe[0]);
63 if (from_child_pipe[1] != STDOUT_FILENO) close(from_child_pipe[1]);
65 exit_cleanup(RERR_IPC);
68 if (close(from_child_pipe[1]) < 0 ||
69 close(to_child_pipe[0]) < 0) {
70 rprintf(FERROR,"Failed to close : %s\n",strerror(errno));
71 exit_cleanup(RERR_IPC);
74 *f_in = from_child_pipe[0];
75 *f_out = to_child_pipe[1];
80 static void sender(int fin, int fout)
86 while (total < TOTAL_SIZE) {
87 n = read(fin, buf, sizeof(buf));
89 fprintf(stderr,"write error in sender at %d\n", total);
92 write_loop(fout, buf, n);
96 fprintf(stderr, "sender done\n");
99 static void generator(int fd)
105 while (total < TOTAL_SIZE) {
106 n = 1 + random() % (sizeof(buf)-1);
107 n = write_loop(fd, buf, n);
109 fprintf(stderr,"write error in generator at %d\n", total);
113 fprintf(stderr, "*");
115 fprintf(stderr, "generator done\n");
118 static void receiver(int fd)
124 while (total < TOTAL_SIZE) {
125 n = read(fd, buf, sizeof(buf));
127 fprintf(stderr,"read error in receiver\n");
131 fprintf(stderr, "+");
133 fprintf(stderr, "receiver done\n");
136 int main(int argc, char *argv[])
140 while ((c = getopt(argc, argv, "s")) != -1) {
151 char *command = argv[1];
152 printf("running %s\n", command);
153 piped_child(command, &f_in, &f_out);