fork download
  1. #include <unistd.h>
  2. #include <fcntl.h>
  3.  
  4. int main(int argc, char* argv[]) {
  5. /**
  6. * pipefd[0]: read end
  7. * pipefd[1]: write end
  8. */
  9. int pipefd[2];
  10. pid_t cat_pid;
  11. pid_t echo_pid;
  12.  
  13. if (pipe(pipefd) < 0) {
  14. perror("pipe");
  15. exit(-1);
  16. }
  17.  
  18. cat_pid = fork();
  19. if (cat_pid == 0) {
  20. close(pipefd[1]); /* close unused end */
  21. dup2(pipefd[0], 0);
  22. execl("/bin/cat", "/bin/cat", NULL);
  23. perror("execl /bin/echo");
  24. return -1;
  25. }
  26.  
  27. echo_pid = fork();
  28. if (echo_pid == 0) {
  29. close(pipefd[0]); /* close unused end */
  30. dup2(pipefd[1], 1);
  31. execl("/bin/echo", "/bin/echo", argv[0], NULL);
  32. perror("execl /bin/echo");
  33. return -1;
  34. }
  35.  
  36. close(pipefd[0]);
  37. close(pipefd[1]);
  38. waitpid(cat_pid, NULL, 0);
  39. waitpid(echo_pid, NULL, 0);
  40. return 0;
  41. }
  42.  
Success #stdin #stdout 0s 3756KB
stdin
123
stdout
./prog