| 1 | #include <stdio.h> |
| 2 | #include <stdlib.h> |
| 3 | #include <string.h> |
| 4 | #include <unistd.h> |
| 5 | |
| 6 | #include <sys/types.h> |
| 7 | #include <sys/wait.h> |
| 8 | |
| 9 | int main() { |
| 10 | int pipefd[2]; |
| 11 | char tmpbuf; |
| 12 | |
| 13 | if (pipe(pipefd) == -1) { |
| 14 | perror("Pipe creation failure\n"); |
| 15 | exit(EXIT_FAILURE); |
| 16 | }; |
| 17 | |
| 18 | pid_t cpid = fork(); |
| 19 | |
| 20 | if (cpid == -1) { |
| 21 | perror("fork failure\n"); |
| 22 | exit(EXIT_FAILURE); |
| 23 | } else if (cpid == 0) { |
| 24 | close(pipefd[0]); |
| 25 | dup2(pipefd[1], STDOUT_FILENO); |
| 26 | execl("/bin/ls", "ls", (char*)NULL); |
| 27 | close(pipefd[1]); |
| 28 | exit(EXIT_SUCCESS); |
| 29 | } else { |
| 30 | close(pipefd[1]); |
| 31 | printf("[%d] REDIRECTION: \n", getpid()); |
| 32 | //determine the pipe size to avoid this kind of code |
| 33 | while (read(pipefd[0], &tmpbuf, 1) > 0) { |
| 34 | write(STDOUT_FILENO, &tmpbuf, 1); |
| 35 | } |
| 36 | close(pipefd[0]); |
| 37 | wait(NULL); |
| 38 | } |
| 39 | |
| 40 | return EXIT_SUCCESS; |
| 41 | } |