/* Pipe example ** This program prints out 10 random numbers in sorted order. ** The sorting is performed by the /bin/sort program - we pipe ** the numbers to this program (with the -n option for sorting numbers). ** To do this, we create a child (so that the pipe can be shared) ** which becomes (execs) the sort program. */ #include #include #include int main(void) { /* Two file descriptors - one for reading, one for writing */ int fd[2]; int pid, i, num; FILE* output; /* Create pipe */ /* Needs to be before we fork! */ if(pipe(fd) == -1) { perror("Can't create pipe"); exit(1); } /* Fork - child and parent now share the same descriptors */ pid = fork(); if(pid) { /* Parent */ /* Close the reading end of the pipe */ close(fd[0]); /* Duplicate - stdout now goes to pipe */ dup2(fd[1], STDOUT_FILENO); /* Don't need two file descriptors - close the duplicate copy */ close(fd[1]); /* Print out some random numbers - output goes to pipe now */ for(i = 0; i< 10; i++) { num = rand(); printf("%d\n", num); } /* Finished writing, close stdout */ fclose(stdout); /* Wait for child to finish */ waitpid(pid, NULL, 0); } else { /* Child */ /* Close the writing end of the pipe */ close(fd[1]); /* Make standard input come from pipe */ dup2(fd[0], STDIN_FILENO); /* Don't need the second file descriptor - they both point the same end of the pipe */ close(fd[0]); /* Exec the sort program... reads from standard input, which is now the pipe, outputs to standard output, which is still the terminal */ execl("/usr/bin/sort", "sort", "-n", NULL); } }