#include #include struct node { int data; struct node * left, * right; }; struct node * constr_node(int d) { struct node * t = (struct node *)malloc(sizeof(struct node)); t->data = d; t->left = NULL; t->right = NULL; return t; } void print(struct node * t) { if (t == NULL) return; printf("("); print(t->left); printf(" %d ", t->data); print(t->right); printf(")"); } void out_tree(struct node * t, int fd) { if (t == NULL) return; out_tree(t->left, fd); write(fd, & t->data, sizeof(t->data)); out_tree(t->right, fd); } struct node * insert(struct node * t, int d) { if (t == NULL) return constr_node(d); if (d < t->data) t->left = insert(t->left, d); else t->right = insert(t->right, d); return t; } void shuffle(int * a, int N) { int i, r, t; for (i = 0; i < 2*N; i += 1) { r = random() % N; t = a[r]; a[r] = a[0]; a[0] = t; } } int main(int argc, char * argv[]) { int number, i, p, comma[2], commb[2]; int * array; struct node * tree1 = NULL, * tree2 = NULL; if (argc != 2) { fprintf(stderr, "usage: %s number-of-numbers\n", argv[0]); exit(1); } number = atol(argv[1]); array = (int *) malloc(sizeof(int) * number); for (i = 0; i < number; i += 1) array[i] = i + 1; srandomdev(); shuffle(array, number); for (i = 0; i < number; i += 1) tree1 = insert(tree1,array[i]); shuffle(array, number); array[2] = random() % 20; for (i = 0; i < number; i += 1) tree2 = insert(tree2,array[i]); print(tree1); printf("\n"); print(tree2); printf("\n"); pipe(comma); pipe(commb); p = fork(); if (p == 0) { close(comma[0]); out_tree(tree1, comma[1]); close(comma[1]); exit(0); } p = fork(); if (p == 0) { close(commb[0]); out_tree(tree2, commb[1]); close(commb[1]); exit(0); } close(comma[1]); close(commb[1]); while (1) { int n1, n2, r; r = read(comma[0], & n1, sizeof(n1)); if (r == 0) break; r = read(commb[0], & n2, sizeof(n2)); if (r == 0) break; printf("received %d and %d\n", n1, n2); } }