]>
Commit | Line | Data |
---|---|---|
d9a17c07 | 1 | /* Creating a Pipe |
2b778ceb | 2 | Copyright (C) 1991-2021 Free Software Foundation, Inc. |
d9a17c07 RM |
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 | |
5a82c748 | 15 | along with this program; if not, see <https://www.gnu.org/licenses/>. |
d9a17c07 RM |
16 | */ |
17 | ||
28f540f4 RM |
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 | ||
a7123f0e | 25 | void |
28f540f4 RM |
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 | ||
a7123f0e | 38 | void |
28f540f4 RM |
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*/ | |
a7123f0e | 55 | /* Create the pipe. */ |
28f540f4 RM |
56 | if (pipe (mypipe)) |
57 | { | |
58 | fprintf (stderr, "Pipe failed.\n"); | |
59 | return EXIT_FAILURE; | |
60 | } | |
61 | /*@end group*/ | |
62 | ||
a7123f0e | 63 | /* Create the child process. */ |
28f540f4 RM |
64 | pid = fork (); |
65 | if (pid == (pid_t) 0) | |
66 | { | |
a7123f0e UD |
67 | /* This is the child process. |
68 | Close other end first. */ | |
69 | close (mypipe[1]); | |
28f540f4 RM |
70 | read_from_pipe (mypipe[0]); |
71 | return EXIT_SUCCESS; | |
72 | } | |
73 | else if (pid < (pid_t) 0) | |
74 | { | |
a7123f0e | 75 | /* The fork failed. */ |
28f540f4 RM |
76 | fprintf (stderr, "Fork failed.\n"); |
77 | return EXIT_FAILURE; | |
78 | } | |
79 | else | |
80 | { | |
a7123f0e UD |
81 | /* This is the parent process. |
82 | Close other end first. */ | |
83 | close (mypipe[0]); | |
28f540f4 RM |
84 | write_to_pipe (mypipe[1]); |
85 | return EXIT_SUCCESS; | |
86 | } | |
87 | } |