#include #include #include #include #include int main(int argc, char *argv[]) { int p2c[2], c2p[2]; if(-1 == pipe(p2c)) { perror("Error creating parent to child pipe"); exit(1); } if(-1 == pipe(c2p)) { perror("Error creating child to parent pipe"); exit(1); } int f = fork(); if(0 > f) { perror("Cannot create child process"); exit(1); } else if (0 == f) { close(p2c[1]); close(c2p[0]); int n = 0; if(-1 == read(p2c[0], &n, sizeof(int))) { perror("Error reading n from parent"); close(p2c[0]); close(c2p[1]); exit(1); } int sum = 0, nr = 0; for(int i = 0; i < n; i++) { if(-1 == read(p2c[0], &nr, sizeof(int))) { perror("Error reading number from parent"); } else { sum += nr; } } if(-1 == write(c2p[1], &sum, sizeof(int))) { perror("Error sending sum to parent"); close(p2c[0]); close(c2p[1]); exit(1); } close(p2c[0]); close(c2p[1]); exit(0); } else { close(p2c[0]); close(c2p[1]); srandom(getpid()); int n; printf("n="); scanf("%d", &n); if(-1 == write(p2c[1], &n, sizeof(int))) { perror("Error writing n to child"); close(p2c[1]); close(c2p[0]); wait(NULL); exit(1); } if(n > 0) { int *arr = malloc(sizeof(int) * n); for(int i = 0; i < n; i++) { arr[i] = random() % 100; printf("a[%d] = %3d\n", i, arr[i]); } if(-1 == write(p2c[1], arr, sizeof(int) * n)) { perror("Error sending array to child"); close(p2c[1]); close(c2p[0]); wait(NULL); exit(1); } free(arr); int sum = 0; if(-1 == read(c2p[0], &sum, sizeof(int))) { perror("Error reading sum from child"); close(p2c[1]); close(c2p[0]); wait(NULL); exit(1); } printf("sum = %d\n", sum); } close(p2c[1]); close(c2p[0]); wait(NULL); } return 0; }