Update.
[glibc.git] / manual / examples / pipe.c
blob054550fec6e774343d2b5064657632625ba4a58e
1 #include <sys/types.h>
2 #include <unistd.h>
3 #include <stdio.h>
4 #include <stdlib.h>
6 /* Read characters from the pipe and echo them to @code{stdout}. */
8 void
9 read_from_pipe (int file)
11 FILE *stream;
12 int c;
13 stream = fdopen (file, "r");
14 while ((c = fgetc (stream)) != EOF)
15 putchar (c);
16 fclose (stream);
19 /* Write some random text to the pipe. */
21 void
22 write_to_pipe (int file)
24 FILE *stream;
25 stream = fdopen (file, "w");
26 fprintf (stream, "hello, world!\n");
27 fprintf (stream, "goodbye, world!\n");
28 fclose (stream);
31 int
32 main (void)
34 pid_t pid;
35 int mypipe[2];
37 /*@group*/
38 /* Create the pipe. */
39 if (pipe (mypipe))
41 fprintf (stderr, "Pipe failed.\n");
42 return EXIT_FAILURE;
44 /*@end group*/
46 /* Create the child process. */
47 pid = fork ();
48 if (pid == (pid_t) 0)
50 /* This is the child process. */
51 read_from_pipe (mypipe[0]);
52 return EXIT_SUCCESS;
54 else if (pid < (pid_t) 0)
56 /* The fork failed. */
57 fprintf (stderr, "Fork failed.\n");
58 return EXIT_FAILURE;
60 else
62 /* This is the parent process. */
63 write_to_pipe (mypipe[1]);
64 return EXIT_SUCCESS;