syslog: Improve fortify with clang
[glibc.git] / manual / examples / pipe.c
blob5dc4dc7eb17be235b225d71f73f37f0022ea5c41
1 /* Creating a Pipe
2 Copyright (C) 1991-2024 Free Software Foundation, Inc.
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.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, see <https://www.gnu.org/licenses/>.
18 #include <sys/types.h>
19 #include <unistd.h>
20 #include <stdio.h>
21 #include <stdlib.h>
23 /* Read characters from the pipe and echo them to @code{stdout}. */
25 void
26 read_from_pipe (int file)
28 FILE *stream;
29 int c;
30 stream = fdopen (file, "r");
31 while ((c = fgetc (stream)) != EOF)
32 putchar (c);
33 fclose (stream);
36 /* Write some random text to the pipe. */
38 void
39 write_to_pipe (int file)
41 FILE *stream;
42 stream = fdopen (file, "w");
43 fprintf (stream, "hello, world!\n");
44 fprintf (stream, "goodbye, world!\n");
45 fclose (stream);
48 int
49 main (void)
51 pid_t pid;
52 int mypipe[2];
54 /*@group*/
55 /* Create the pipe. */
56 if (pipe (mypipe))
58 fprintf (stderr, "Pipe failed.\n");
59 return EXIT_FAILURE;
61 /*@end group*/
63 /* Create the child process. */
64 pid = fork ();
65 if (pid == (pid_t) 0)
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;
73 else if (pid < (pid_t) 0)
75 /* The fork failed. */
76 fprintf (stderr, "Fork failed.\n");
77 return EXIT_FAILURE;
79 else
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;