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