fork(2) download
  1. #include <errno.h> // errno, EINTR
  2. #include <stdio.h> // perror
  3. #include <stdlib.h> // exit
  4. #include <unistd.h> // _exit, close, dup2, execl, fork, pipe, STDOUT_FILENO
  5. #include <sys/wait.h> // wait, pid_t
  6.  
  7.  
  8. void handle_child_process_output(char *buffer, ssize_t count);
  9.  
  10. int main(void)
  11. {
  12. int filedes[2];
  13. if (pipe(filedes) == -1)
  14. {
  15. perror("pipe");
  16. exit(EXIT_FAILURE);
  17. }
  18. pid_t pid = fork();
  19. if (pid == -1)
  20. {
  21. perror("fork");
  22. exit(EXIT_FAILURE);
  23. }
  24. else if (pid == 0)
  25. {
  26. while ((dup2(filedes[1], STDOUT_FILENO) == -1 && (errno == EINTR)))
  27. {
  28. continue;
  29. }
  30. fprintf(stdout,"point 1\n");
  31.  
  32. close(filedes[1]);
  33. close(filedes[0]);
  34. fprintf(stdout,"point 2\n");
  35.  
  36. static char *argv[] = {"echo", "Sphinx of black quartz, judge my vow.", NULL};
  37. execv("/bin/echo", argv);
  38. exit(EXIT_FAILURE); // only if execv fails
  39. }
  40. close(filedes[1]);
  41.  
  42. // at this point filedes[1] is open in child process to be written in
  43. // and filedes[0] is open in parent process to be read from
  44. char buffer[4096];
  45. for (;;)
  46. {
  47. ssize_t count = read(filedes[0], buffer, sizeof(buffer));
  48. if (count == -1)
  49. {
  50. if (errno == EINTR)
  51. {
  52. continue;
  53. }
  54. else
  55. {
  56. perror("read");
  57. exit(EXIT_FAILURE);
  58. }
  59. }
  60. else if (count == 0)
  61. {
  62. break;
  63. }
  64. else
  65. {
  66. handle_child_process_output(buffer, count);
  67. }
  68. }
  69. close(filedes[0]);
  70. wait(NULL);
  71. }
  72.  
  73. void handle_child_process_output(char *buffer, ssize_t count)
  74. {
  75. printf("%s", "\x1b[34m");
  76. fwrite(buffer, count, sizeof(buffer[0]), stdout);
  77. printf("%s", "\x1b[0m");
  78. }
Success #stdin #stdout 0s 4504KB
stdin
Standard input is empty
stdout
Sphinx of black quartz, judge my vow.