pipe.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* Creating a Pipe
  2. Copyright (C) 1991-2019 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either version 2
  6. of the License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <sys/types.h>
  15. #include <unistd.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. /* Read characters from the pipe and echo them to @code{stdout}. */
  19. void
  20. read_from_pipe (int file)
  21. {
  22. FILE *stream;
  23. int c;
  24. stream = fdopen (file, "r");
  25. while ((c = fgetc (stream)) != EOF)
  26. putchar (c);
  27. fclose (stream);
  28. }
  29. /* Write some random text to the pipe. */
  30. void
  31. write_to_pipe (int file)
  32. {
  33. FILE *stream;
  34. stream = fdopen (file, "w");
  35. fprintf (stream, "hello, world!\n");
  36. fprintf (stream, "goodbye, world!\n");
  37. fclose (stream);
  38. }
  39. int
  40. main (void)
  41. {
  42. pid_t pid;
  43. int mypipe[2];
  44. /*@group*/
  45. /* Create the pipe. */
  46. if (pipe (mypipe))
  47. {
  48. fprintf (stderr, "Pipe failed.\n");
  49. return EXIT_FAILURE;
  50. }
  51. /*@end group*/
  52. /* Create the child process. */
  53. pid = fork ();
  54. if (pid == (pid_t) 0)
  55. {
  56. /* This is the child process.
  57. Close other end first. */
  58. close (mypipe[1]);
  59. read_from_pipe (mypipe[0]);
  60. return EXIT_SUCCESS;
  61. }
  62. else if (pid < (pid_t) 0)
  63. {
  64. /* The fork failed. */
  65. fprintf (stderr, "Fork failed.\n");
  66. return EXIT_FAILURE;
  67. }
  68. else
  69. {
  70. /* This is the parent process.
  71. Close other end first. */
  72. close (mypipe[0]);
  73. write_to_pipe (mypipe[1]);
  74. return EXIT_SUCCESS;
  75. }
  76. }