Add two forgotten licence exceptions
[glibc.git] / manual / examples / pipe.c
blob92d339a7b9fb0c0fcf6a1aa7983adaf11abdfd28
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 Close other end first. */
52 close (mypipe[1]);
53 read_from_pipe (mypipe[0]);
54 return EXIT_SUCCESS;
56 else if (pid < (pid_t) 0)
58 /* The fork failed. */
59 fprintf (stderr, "Fork failed.\n");
60 return EXIT_FAILURE;
62 else
64 /* This is the parent process.
65 Close other end first. */
66 close (mypipe[0]);
67 write_to_pipe (mypipe[1]);
68 return EXIT_SUCCESS;